package com.dminvoicemanager;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import java.util.List;
import com.dminvoicemanager.DM_InvoiceDetails.DecimalDigitsInputFilter;
import com.dminvoicemanager.adapters.DM_CustomerList_Adapter;
import com.dminvoicemanager.adapters.DM_SalesOrder_Alert_Adapter;
import com.dminvoicemanager.printdoc.DM_Print_Main_Invoice;
import com.dminvoicemanager.reports.DM_Customer_Last_Three_Visit;
import com.dminvoicemanager.tabs.DM_RetOutstanding_Information;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.ActionBar.OnNavigationListener;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public class DM_InvoiceNew extends Activity {
	// private PBDatabaseAdapter dbHelper;
	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	private String USER_SETTINGS = "usersettings";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String INV_SAL_REP = "fSalRep";
	private String RECEIPT_DETAILS = "fDRecDet";
	// Main Invoice
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";

	// Stock Loading
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhedLo";
	private String STOCK_LOAD_DETAIL = "fLoadDet";

	// Stock Loading
	private String STOCK_ORDER_INVOICESUMERY = "fstockordInvoiceSumery";
	private String STOCK_ORDER_HEAD = "FOrdHed";
	private String STOCK_ORDER_DETAIL = "FOrddet";

	private String RECEIPT_INVOICES = "FDDbNote";

	private SQLiteDatabase mydb;

	final private static int DIALOG_CANCEL_INVOICE = 1;
	final private static int DIALOG_UNDO_INVOICE = 2;
	final private static int DIALOG_PRINT_INVOICE = 3;
	final private static int DIALOG_SAVE_INVOICE = 4;
	final private static int DIALOG_SELECT_CUSTOMER = 5;
	final private static int DIALOG_MUSTSALE_ITEMS = 6;
	private static final String TAG = null;

	AlertDialog InvoiceHeaderAlert = null;
	Dialog invoiceListDialog;
	String TagId, ItmTxnType, invDiliveryDate;
	int ListInvTag = 0, StockLoadMap = 0, IVOICEITEMSCHK = 0, CANCELTAG = 0,
			SAVETAG = 0, receiptCount;
	EditText etdminvdate, etdminvcustomer, etdminvremarks, etdminvcusdis,
			etdminvdiscount, dminvfiltercustomer, myFilterCustomer;
	Button INVSelectCustomer, INVSelectItems, INVSave, INVPrint, INVCancel,
			INVUndo, etdminvno, etdmstorderno, popup_invmenubut,
			CusListAllViewBtn;
	LinearLayout ListViewShowCustomers, ListViewInvHeaderButton,
			ListViewInvHeaderDetails, ListViewselectinvoices,
			ListViewselectstockorders;
	RelativeLayout customerSearchBox;
	String match = "5";
	String invoiceSerial, InvoiceCustomerCode, LatestInvNumberStr,
			OutDisSumUpdate, OutDisValSumUpdate, CustomerCodeInv;
	String PrintTotalDiscountValue, PrintDiscountedInvValueItems,
			PrintTotCustomerInvDiscount, UnitPrice = "0";
	String invcuscode, invcusname, invcusdiscount, currentInvoiceTempRefCode,
			invheadcode, currentSerial, currentPreInvoiceCode,
			currentStRefNoUser, strLatestInvoiceSerial, deviceModel,
			deviceUser = "ANDROID", UserDealCode, UserAreaCode, UserRouteCode,
			InvoiceRefSalesOrdNo;
	EditText marketretval, invoicetotval, invoicedisval, etdminvCusdiscount;
	double InvDiscountValueItems = 0.0, InvValueItems = 0.0,
			InvValueItemsReturned = 0.0, InvDiscountValueCustomer = 0.0,
			TotCustomerInvDiscount = 0.0, TotalDiscountValue = 0.0,
			DiscountedInvValueItems = 0.0, RefNoItemQty = 0.0,
			CurrentStockVal = 0.0, ItemsDisCusValuePer = 0.0,
			ItemsCusManualDisValue = 0.0, InvoicePreInvDisRaioVal = 0.0,
			discountRationVal = 0.00;
	double StrInvDisRatioAmount = 0.00;
	double StrInvDisRatioAmountManu = 0.00;
	double ratio = 0.00;
	double ratioManu = 0.00;
	double StrManualInvAmount = 0.00;
	double StrManualInvAmountManu = 0.00;
	double StrManualDiscount = 0.00;
	double StrMainInvValTot = 0.00;
	double StrMainInvDisValTot = 0.00;
	double StrMainLineDisValTot = 0.00;
	double CurrentItemStockQty = 0.00;
	Double noOfAdjustedCases = 0.00;
	Double noOfAdjustedPieces = 0.00;

	double RecheckInvoiceValue = 0.00;
	double RecheckInvoiceDiscount = 0.00;
	double RecheckInvoiceValReturn = 0.00;

	// Invoice total
	double activeInvoiceVal = 0.0, currentInvTotalVal = 0.0;
	String activeInvoiceCode = "1", currentUserTemp, currentUserPrefix,
			refNoSummaryInvoice, refNoStockOrderInvoice, UserLocCode;

	String RepInvCode, TransTypePrefix, AgentPrefixType, LatestInvNumber,
			LatestInvState, ActiveInvoice, slectedMenuOption, SalesOrderRef,
			currentItemCode, currentQty;
	int ButtonTag, NoOfItemsPerInvoice = 0, customerReloadTag = 202,
			CHKINVSETTLEMENT = 0, TEXTCHANGEACTIVE = 0, INVICEDCUSTAG = 0;
	DecimalFormat formatValues = new DecimalFormat("#,###,##0.00");

	/** An array of strings to populate dropdown list */
	String[] actions = new String[] { "Select Options", "Last Three Visit",
			"Last Invoice" };
	String StockOutItems = "", QtyAdjustedItems = "";
	int STOCKCHK = 0, SONULLCHECKED = 0;
	String stringArray = "";
	private DM_CustomerList_Adapter dbHelperCustomer;
	private SimpleCursorAdapter dataAdapterCusomer;
	private ArrayList<String> array_sort;
	int textlength = 0;
	private AlertDialog myalertDialog = null;
	private String TitleName[];
	String mainDelvDate;

	public void ExitFromForm(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
	}

	// ============Cancel Invoice===================
	public void btnCancelInvoice(View view) {
		checkInvoiceUploaded();
	}

	private void checkInvoiceUploaded() {
		// TODO Auto-generated method stub
		String currentRef = etdminvno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor chkInvoiceUpload = null;
		try {
			chkInvoiceUpload = mydb.query(INV_HEADER, null, "RefNo='"
					+ currentRef + "' AND invhedSync ='1'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (chkInvoiceUpload != null) {
			if (chkInvoiceUpload.getCount() > 0) {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_InvoiceNew.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("ERROR CANCEL INVOICE");
				// Setting Dialog Message
				alertDialog
						.setMessage("Selected Invoice Already Uploaded.Not Authorized To Cancel..");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			} else {
				checkInvoiceSettlement();
				if (CHKINVSETTLEMENT == 30) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_InvoiceNew.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("CANCEL INVALID INVOICE");
					// Setting Dialog Message
					alertDialog
							.setMessage("Current Not Allow to Cancel.Invoice Already Settle...");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									CANCELTAG = 0;
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				} else {
					etdmstorderno.setEnabled(true);
					checkInvoiceSaved();
					if (CANCELTAG == 45) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceNew.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("CANCEL INVALID INVOICE");
						// Setting Dialog Message
						alertDialog.setMessage("Current Invoice Not Saved..");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										CANCELTAG = 0;
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					} else {
						if (etdminvno.length() != 0) {
							try {
								ButtonTag = 3;
								showDialog(DIALOG_CANCEL_INVOICE);
							} catch (Exception ex) {
								ex.printStackTrace();
							}
						} else {
							ShowInvoiceList();
						}
					}
				}

			}
		}
		chkInvoiceUpload.close();
		mydb.close();
	}

	private void checkInvoiceSettlement() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****checkInvoiceSettlement*****");
		String CurrentInvoiceRefNoChk = etdminvno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor CurrentChkRecInv = null;
		try {
			CurrentChkRecInv = mydb.query(RECEIPT_DETAILS, null, "RefNo1='"
					+ CurrentInvoiceRefNoChk + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (CurrentChkRecInv != null) {
			if (CurrentChkRecInv.getCount() > 0) {
				CHKINVSETTLEMENT = 30;
				// Log.v(TAG, "CHKINVSETTLEMENT 1:" + CHKINVSETTLEMENT);
			} else {
				CHKINVSETTLEMENT = 0;
				// Log.v(TAG, "CHKINVSETTLEMENT 2:" + CHKINVSETTLEMENT);
			}
		}
	}

	private void checkInvoiceSaved() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****checkInvoiceSaved*****");
		String CurrentInvoiceRefNoChk = etdminvno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor CurrentStLoadRefCur = null;
		try {
			CurrentStLoadRefCur = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"repusername='" + currentUserTemp + "' AND invoiceRef='"
							+ CurrentInvoiceRefNoChk + "'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (CurrentStLoadRefCur != null) {
			if (CurrentStLoadRefCur.getCount() > 0) {
				CANCELTAG = 0;
				SAVETAG = 99;
			} else {
				CANCELTAG = 45;
			}
		}
		CurrentStLoadRefCur.close();
		mydb.close();
	}

	// Undo Invoice Handling
	public void btnCancelInvoiceReject(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	public void btnCancelInvoiceAccept(View view) {
		// synchdata();
		invoiceTransType();
		agentPrefix();
		if (ListInvTag != 99) {
			latestInvoiceRecord();
			SaveMainInvoice(); // 1
			// Log.v(TAG, "**** SaveMainInvoice CALL 1");
		}
		// Update fItemLoc Items Quantity
		UpdateStockQuantityOnCancel();
		// Update Sync State Not To upload Canceled Invoices
		// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		UpdateSyncStateOnCancel();
		updateInvoiceCancelState();
		// Check Refering Sales Order - 04/01/2014
		UpdateSalesOrder();
		// Remove FDDbNote Record for the Invoice - 04/01/2014
		UpdateFDDbNoteRecord();
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
	}

	private void UpdateFDDbNoteRecord() {
		// TODO Auto-generated method stub
		String RefNoCode = etdminvno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUpdateFDDbNote = null;

		try {
			curUpdateFDDbNote = mydb.query(RECEIPT_INVOICES, null, "RefNo='"
					+ RefNoCode + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (curUpdateFDDbNote != null) {
			if (curUpdateFDDbNote.getCount() > 0) {
				while (curUpdateFDDbNote.moveToNext()) {
					mydb.delete(RECEIPT_INVOICES, "RefNo ='" + RefNoCode + "'",
							null);
				}
			}
		}
		curUpdateFDDbNote.close();
		mydb.close();
	}

	private void UpdateSalesOrder() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUpdateSalesOrdState = null;

		try {
			curUpdateSalesOrdState = mydb.query(STOCK_ORDER_HEAD, null,
					"RefNo='" + InvoiceRefSalesOrdNo + "'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (curUpdateSalesOrdState != null) {
			if (curUpdateSalesOrdState.getCount() > 0) {
				while (curUpdateSalesOrdState.moveToNext()) {
					ContentValues conInvOrdHedStateUpdate = new ContentValues();
					String RefOrdId = curUpdateSalesOrdState.getString(16);
					conInvOrdHedStateUpdate.put("stOrderComplete", "0");
					mydb.update(STOCK_ORDER_HEAD, conInvOrdHedStateUpdate,
							"RefNo ='" + RefOrdId + "'", null);
				}
			}
		}
		curUpdateSalesOrdState.close();
		mydb.close();
	}

	// Update Sync State Not To upload Canceled Invoices
	private void UpdateSyncStateOnCancel() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****UpdateSyncState*****");
		String RefNoCode = etdminvno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUpdateSyncStateInvHed = null;
		Cursor curUpdateSyncStateInvDet = null;

		try {
			curUpdateSyncStateInvHed = mydb.query(INV_HEADER, null, "RefNo='"
					+ RefNoCode + "'", null, null, null, null);
		} catch (Exception e) {
		}

		try {
			curUpdateSyncStateInvDet = mydb.query(INV_DETAILS, null, "RefNo='"
					+ RefNoCode + "'", null, null, null, null);
		} catch (Exception e) {
		}

		if (curUpdateSyncStateInvHed != null) {
			if (curUpdateSyncStateInvHed.getCount() > 0) {
				while (curUpdateSyncStateInvHed.moveToNext()) {
					ContentValues conInvHedValUpdate = new ContentValues();
					String StrinvhedRef = curUpdateSyncStateInvHed.getString(1);
					InvoiceRefSalesOrdNo = curUpdateSyncStateInvHed
							.getString(2);
					conInvHedValUpdate.put("invhedSync", "3");
					mydb.update(INV_HEADER, conInvHedValUpdate, "RefNo ='"
							+ StrinvhedRef + "'", null);
				}
			}
		}

		if (curUpdateSyncStateInvDet != null) {
			if (curUpdateSyncStateInvDet.getCount() > 0) {
				while (curUpdateSyncStateInvDet.moveToNext()) {
					ContentValues conInvDetValUpdate = new ContentValues();
					String StrinvdetRef = curUpdateSyncStateInvDet.getString(1);
					conInvDetValUpdate.put("invdetSync", "3");
					mydb.update(INV_DETAILS, conInvDetValUpdate, "RefNo ='"
							+ StrinvdetRef + "'", null);
				}
			}
		}
	}

	// ==============Undo Invoice====================
	public void btnUndoInvoice(View view) {
		etdmstorderno.setEnabled(true);
		if (etdminvno.length() != 0) {
			try {
				showDialog(DIALOG_UNDO_INVOICE);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
			try {
				showDialog(DIALOG_UNDO_INVOICE);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

	// Undo Invoice Handling
	public void btnUndoInvoiceCancel(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	public void btnUndoInvoiceAccept(View view) {
		etdmstorderno.setEnabled(true);
		INVSelectCustomer.setEnabled(true);
		INVSelectItems.setEnabled(true);
		invoicedisval.setText("");
		invoicetotval.setText("");
		invoiceTransType();
		agentPrefix();
		if (ListInvTag != 99) {
			if (etdminvno.length() != 0 || ListInvTag == 77) {
				latestInvoiceRecord();
				updateInvoiceUndoState();
				clearInvoiceUndoFields();
				InvoiceHeaderAlert.dismiss();
			}

		} else if (ListInvTag == 99 || ListInvTag == 77) {
			latestInvoiceRecord();
			updateInvoiceUndoState();
			clearInvoiceUndoFields();
			InvoiceHeaderAlert.dismiss();
		}

		InvoiceHeaderAlert.dismiss();
	}

	public void btnUndoInvoiceAcceptExit(View view) {
		etdmstorderno.setEnabled(true);
		INVSelectCustomer.setEnabled(true);
		INVSelectItems.setEnabled(true);
		invoiceTransType();
		agentPrefix();
		if (ListInvTag != 99) {
			if (etdminvno.length() != 0 || ListInvTag == 77) {
				latestInvoiceRecord();
				updateInvoiceUndoState();
				clearInvoiceUndoFields();
				InvoiceHeaderAlert.dismiss();
			}

		} else if (ListInvTag == 99 || ListInvTag == 77) {
			latestInvoiceRecord();
			updateInvoiceUndoState();
			clearInvoiceUndoFields();
			InvoiceHeaderAlert.dismiss();

		}
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		InvoiceHeaderAlert.dismiss();
	}

	private void clearInvoiceUndoFields() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****clearInvoiceUndoFields*****");
		ratioManu = 0.00;
		StrManualInvAmount = 0.00;
		StrManualInvAmountManu = 0.00;
		StrMainInvDisValTot = 0.00;
		StrManualDiscount = 0.00;
		StrMainInvValTot = 0.00;
		StrMainLineDisValTot = 0.00;
		etdminvno.setText("");
		etdmstorderno.setText("");
		etdminvdate.setText(getCurrentTimeStringCustom().toString());
		etdminvcustomer.setText("");
		etdminvremarks.setText("");
		etdminvcusdis.setText("");
		etdminvdiscount.setText("");
		marketretval.setText("");
		invoicedisval.setText("");
		invoicetotval.setText("");
		etdminvCusdiscount.setText("");

	}

	// ------------------List Invoice Dialog Dissmis-----------------
	public void btnClickDialogDissmiss(View view) {
		invoiceListDialog.dismiss();
	}

	// ------------------Print Invoice-----------------
	public void btnPrintInvoice(View view) {
		if (etdminvno.length() != 0) {
			checkInvoiceSaved();

			if (SAVETAG == 99) {
				String currentPrintRefNo = etdminvno.getText().toString();
				Intent myIntent = new Intent(view.getContext(),
						DM_Print_Main_Invoice.class);
				myIntent.putExtra("TAGIDREFNO", currentPrintRefNo);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			} else {
				SAVETAG = 0;
				showDialog(DIALOG_PRINT_INVOICE);
			}
		} else {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceNew.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("SELECT INVOICE");
			// Setting Dialog Message
			alertDialog.setMessage("Select Valid Invoice");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}
	}

	// Undo Invoice Handling
	public void btnPrintInvoiceCancel(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	public void btnPrintInvoiceAccept(View view) {
		// InvoiceHeaderAlert.dismiss();
		SaveMainInvoice(); // 2
		// Log.v(TAG, "**** SaveMainInvoice CALL 2");
		String currentPrintRefNo = etdminvno.getText().toString();
		Intent myIntent = new Intent(view.getContext(),
				DM_Print_Main_Invoice.class);
		myIntent.putExtra("TAGIDREFNO", currentPrintRefNo);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
	}

	// =======Save Invoice========

	// Save invoice details and invoice header details to activate invoice
	public void btnSaveInvoice(View view) {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				DM_InvoiceNew.this);
		builder.setTitle("SAVE NEW INVOICE");
		builder.setMessage("Are Sure You Want To Save This Invoice...");
		builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				checkMustSalesItems();
			}
		});
		builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(),
						"Cancel Save Invoice..", Toast.LENGTH_LONG).show();
			}
		});
		builder.show();
	}

	private void checkMustSalesItems() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****checkMustSalesItems*****");
		String currentInvNoRef = etdminvno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor curChkItemsMust = null;
		try {
			String queryMustSale = "SELECT ID.RefNo,ID.Itemcode,ID.Type,IM.ItemCode FROM FinvDet ID,fItems IM Where ID.RefNo = '"
					+ currentInvNoRef
					+ "' AND ID.Itemcode = IM.ItemCode AND IM.MustSale = '1' AND ID.Type ='SA' group by ID.Itemcode";
			curChkItemsMust = mydb.rawQuery(queryMustSale, null);

		} catch (Exception e) {
		}
		if (curChkItemsMust != null) {
			if (curChkItemsMust.getCount() > 0) {
				checkInvItemsAvailable();
				/*
				 * while (curChkItemsMust.moveToNext()) {
				 * 
				 * }
				 */
			} else {
				try {
					showDialog(DIALOG_MUSTSALE_ITEMS);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				return;
			}
		}
	}

	public void btnCancelMustSalesNo(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
		checkInvItemsAvailable();

	}

	// Must Sale Yes
	public void btnCancelMustSalesYes(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	private void checkInvItemsAvailable() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****checkInvItemsAvailable*****");
		String currentInvNoRef = etdminvno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor curChkItems = null;
		try {
			curChkItems = mydb.query(INV_DETAILS, null, "RefNo='"
					+ currentInvNoRef + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (curChkItems != null) {
			if (curChkItems.getCount() > 0) {
				IVOICEITEMSCHK = 101;
			} else {
				IVOICEITEMSCHK = 102;
			}
		}
		saveInvoice();
	}

	private void saveInvoice() {
		// TODO Auto-generated method stub
		if (IVOICEITEMSCHK == 101) {
			ButtonTag = 2;
			SaveMainInvoice(); // 3
			// Log.v(TAG, "**** SaveMainInvoice CALL 3");
		} else {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceNew.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("INVALID INVOICE");
			// Setting Dialog Message
			alertDialog.setMessage("Items Not Found For Current Invoice..");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}
	}

	public void btnSaveInvoiceAccept(View view) {
		if (etdminvno.length() != 0) {
			Intent myIntent = new Intent(view.getContext(),
					DM_InvoiceMenu.class);
			myIntent.putExtra("TAGID", "SALES");
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			InvoiceHeaderAlert.dismiss();
			finish();

		} else {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceNew.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("INVOICE ERROR");
			// Setting Dialog Message
			alertDialog.setMessage("Invoice Not Found");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

	}

	// ------------------Select Customer Invoice-----------------
	public void btnSelectCustomerAccept(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	// Back to Invoice header without selecting Customer
	public void btnCusListBack(View view) {
		customerReloadTag = 202;
		ListViewShowCustomers.setVisibility(view.GONE);
		ListViewselectinvoices.setVisibility(view.GONE);
		ListViewselectstockorders.setVisibility(view.GONE);
		ListViewInvHeaderButton.setVisibility(view.VISIBLE);
		ListViewInvHeaderDetails.setVisibility(view.VISIBLE);
	}

	private void SaveMainInvoice() {
		// Log.v(TAG, "999 ** SaveMainInvoice CALL Method");
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues addnewInvoiceHeader = new ContentValues();
			addnewInvoiceHeader.put("RefNo", etdminvno.getText().toString());
			addnewInvoiceHeader.put("RefNo1", etdmstorderno.getText()
					.toString());
			addnewInvoiceHeader.put("InvType", "1");
			addnewInvoiceHeader
					.put("TxnDate", etdminvdate.getText().toString());
			addnewInvoiceHeader.put("ManuRef", "");
			addnewInvoiceHeader.put("DealCode", UserDealCode);
			addnewInvoiceHeader.put("RepCode", currentUserTemp);
			addnewInvoiceHeader.put("AreaCode", UserAreaCode);
			addnewInvoiceHeader.put("RouteCode", UserRouteCode);
			addnewInvoiceHeader.put("DebCode", invcuscode);
			addnewInvoiceHeader.put("LocCode", UserLocCode);
			addnewInvoiceHeader.put("Remarks", etdminvremarks.getText()
					.toString());
			addnewInvoiceHeader.put("CostCode", "000");
			addnewInvoiceHeader.put("CurCode", "LKR");
			addnewInvoiceHeader.put("CurRate", "1.00");
			addnewInvoiceHeader.put("TxnType", "22");

			String discountedamount = invoicetotval.getText().toString();
			String invdiscount = etdminvdiscount.getText().toString();
			double discountedamountVal = Double.parseDouble(discountedamount
					.replaceAll("[,]", ""));
			double invdiscountVal = Double.parseDouble(invdiscount.replaceAll(
					"[,]", ""));

			double adjustinvamount = discountedamountVal + invdiscountVal;
			adjustinvamount = Math.round(adjustinvamount * 100) / 100.0d;
			String Printadjustinvamount = Double.toString(adjustinvamount);

			addnewInvoiceHeader.put("InvAmt", invoicetotval.getText()
					.toString().replaceAll("[,]", ""));
			if (etdminvcusdis.length() != 0) {
				addnewInvoiceHeader.put("OutDis", etdminvcusdis.getText()
						.toString());
			} else {
				addnewInvoiceHeader.put("OutDis", "0.00");
			}

			if (invoicedisval.length() != 0) {
				addnewInvoiceHeader.put("InvDis", etdminvdiscount.getText()
						.toString());
			} else {
				addnewInvoiceHeader.put("InvDis", "0.00");
			}
			if (marketretval.length() != 0) {
				addnewInvoiceHeader.put("TotMkrAmt", marketretval.getText()
						.toString().replaceAll("[,]", ""));
			} else {
				addnewInvoiceHeader.put("TotMkrAmt", "0.00");
			}

			addnewInvoiceHeader.put("UnOvAmt", "0.00");
			if (invoicedisval.length() != 0) {
				addnewInvoiceHeader.put("TotalDis", invoicedisval.getText()
						.toString());
			} else {
				addnewInvoiceHeader.put("TotalDis", "0.00");
			}
			addnewInvoiceHeader.put("TotalAmt", invoicetotval.getText()
					.toString().replaceAll("[,]", ""));
			addnewInvoiceHeader.put("AddUser", currentUserTemp);
			addnewInvoiceHeader.put("AddDateInvHead", getAddDateTimeString()
					.toString());
			addnewInvoiceHeader.put("AddMach", deviceUser);
			addnewInvoiceHeader.put("prtcopy", "0");
			addnewInvoiceHeader.put("RecordId", "1");
			addnewInvoiceHeader.put("timestamp_column",
					getCurrentTimeStringCustom().toString());

			invheadcode = etdminvno.getText().toString();
			String[] accountdetail = invheadcode.split("/");
			String invSerialCode = accountdetail[0]; // invSerialCode
			String invSerialNo = accountdetail[1]; // invSerialNo
			Integer i = new Integer(invSerialNo);
			int Serialnum = i.intValue();
			currentSerial = Integer.toString(Serialnum);

			addnewInvoiceHeader.put("refInvoiceHeaderNo", currentSerial);
			addnewInvoiceHeader.put("refInvoiceHeaderCode", etdminvno.getText()
					.toString());
			addnewInvoiceHeader.put("invhedSync", "0");
			String PreFinalValPerItemSave = "0.00";
			if (etdminvCusdiscount.length() != 0) {
				String outDisValStr = etdminvCusdiscount.getText().toString();
				double outDisValue = Double.parseDouble(outDisValStr
						.replaceAll("[,]", ""));
				PreFinalValPerItemSave = formatValues.format(outDisValue);
			}

			addnewInvoiceHeader.put("outDisVal", PreFinalValPerItemSave);
			mydb.insert(INV_HEADER, null, addnewInvoiceHeader);
			// Log.v(TAG, "###########+++++++++==========&&&&&&&&&###########");
			if (etdmstorderno.length() != 0) {
				SalesOrderRef = etdmstorderno.getText().toString();
				updateStockOrder();
			}
			insertFDDbNote();
			UpdateStockQuantity();
			invoiceTransType();
			agentPrefix();
			latestInvoiceRecord();

			updateInvoiceCurrentState();
			if (ButtonTag == 2) {
				try {
					showDialog(DIALOG_SAVE_INVOICE);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			addNewInvoice();

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured A..",
					Toast.LENGTH_SHORT).show();
		}
		mydb.close();

	}

	private void updateStockOrder() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****updateStockOrder*****");
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor checkOrdNo = null;
		try {
			checkOrdNo = mydb.query(STOCK_ORDER_HEAD, null, "RefNo='"
					+ SalesOrderRef + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (checkOrdNo != null) {
			if (checkOrdNo.getCount() > 0) {
				while (checkOrdNo.moveToNext()) {
					ContentValues udateChkOrdNo = new ContentValues();
					udateChkOrdNo.put("InvFlg", "1");
					udateChkOrdNo.put("stOrderComplete", "1");
					mydb.update(STOCK_ORDER_HEAD, udateChkOrdNo, "RefNo ='"
							+ SalesOrderRef.trim() + "'", null);
				}
			}
		}
		checkOrdNo.close();
		mydb.close();

	}

	private void insertFDDbNote() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****insertFDDbNote*****");
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		receiptCount = receiptCount + 1;
		try {
			ContentValues newrowfDdbNote = new ContentValues();
			newrowfDdbNote.put("RecordId", receiptCount);
			newrowfDdbNote.put("RefNo", etdminvno.getText().toString());
			newrowfDdbNote.put("RefInv", etdminvno.getText().toString());
			newrowfDdbNote.put("SaleRefNo", "");
			newrowfDdbNote.put("ManuRef", "");
			newrowfDdbNote.put("TxnType", "10");
			newrowfDdbNote.put("TxnDate", getCurrentTimeStringCustom()
					.toString());
			newrowfDdbNote.put("CurCode", "LKR");
			newrowfDdbNote.put("CurRate", "1.00");
			newrowfDdbNote.put("DebCode", invcuscode);
			newrowfDdbNote.put("RepCode", currentUserTemp);
			newrowfDdbNote.put("TaxComCode", "");
			newrowfDdbNote.put("TaxAmt", "0.00");
			newrowfDdbNote.put("BTaxAmt", "0.00");
			newrowfDdbNote.put("Amt", invoicetotval.getText().toString()
					.replaceAll("[,]", ""));
			newrowfDdbNote.put("BAmt", invoicetotval.getText().toString()
					.replaceAll("[,]", ""));
			newrowfDdbNote.put("TotBal", invoicetotval.getText().toString()
					.replaceAll("[,]", ""));
			newrowfDdbNote.put("TotBal1", "0.00");
			newrowfDdbNote.put("OvPayAmt", "0.00");
			newrowfDdbNote.put("Remarks", etdminvremarks.getText().toString());
			newrowfDdbNote.put("CrAcc", "00000009-000");
			newrowfDdbNote.put("PrtCopy", "0");
			newrowfDdbNote.put("GlPost", "Y");
			newrowfDdbNote.put("glbatch", "");
			newrowfDdbNote.put("AddUser", "");
			newrowfDdbNote.put("AddDate", "");
			newrowfDdbNote.put("AddMach", deviceUser);
			newrowfDdbNote.put("RefNo1", "");
			mydb.insert(RECEIPT_INVOICES, null, newrowfDdbNote);
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured B..",
					Toast.LENGTH_SHORT).show();
		}
	}

	private void UpdateStockQuantity() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****UpdateStockQuantity*****");
		String RefNoCode = etdminvno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUpdateBalQty = null;
		Cursor curUpdateItemLocBalQty = null;
		try {
			curUpdateBalQty = mydb.query(INV_DETAILS, null, "RefNo='"
					+ RefNoCode + "'", null, null, null, null);
		} catch (Exception e) {
		}

		if (curUpdateBalQty != null) {
			if (curUpdateBalQty.getCount() > 0) {
				while (curUpdateBalQty.moveToNext()) {
					String StrRefNoItemTxn = curUpdateBalQty.getString(3);
					String RefNoItemCode = curUpdateBalQty.getString(5);
					String StrRefNoItemQty = curUpdateBalQty.getString(15);

					/*
					 * Log.v(TAG, "QOH :" + RefNoCode + ":" + RefNoItemCode +
					 * "=" + UserLocCode);
					 */
					RefNoItemQty = Double.parseDouble(StrRefNoItemQty);
					// Update Items Location Quantities UserLocCode
					try {
						curUpdateItemLocBalQty = mydb
								.query(ITEM_LOC_DETAILS, null, "Itemcode='"
										+ RefNoItemCode + "' AND LocCode='"
										+ UserLocCode + "'", null, null, null,
										null);
					} catch (Exception e) {
					}

					if (curUpdateItemLocBalQty != null) {
						if (curUpdateItemLocBalQty.getCount() > 0) {
							while (curUpdateItemLocBalQty.moveToNext()) {
								ContentValues valueUpdateCurStock = new ContentValues();
								String StrCurrentStock = curUpdateItemLocBalQty
										.getString(3);
								String StrCurRecordId = curUpdateItemLocBalQty
										.getString(4);
								if (StrRefNoItemTxn.equals("22")
										|| StrRefNoItemTxn.equals("27")) {
									CurrentStockVal = Double
											.parseDouble(StrCurrentStock);
									/*
									 * Log.v(TAG, "QOH UPDATE:" +
									 * CurrentStockVal + "-" + RefNoItemQty);
									 */
									CurrentStockVal = CurrentStockVal
											- RefNoItemQty;
									String PrintCurrentStockVal = Double
											.toString(CurrentStockVal);
									valueUpdateCurStock.put("QOH",
											PrintCurrentStockVal);
									valueUpdateCurStock.put("syncRec", "0");
									mydb.update(ITEM_LOC_DETAILS,
											valueUpdateCurStock, "RecordId ='"
													+ StrCurRecordId + "'",
											null);
								} else if (StrRefNoItemTxn.equals("25")
										|| StrRefNoItemTxn.equals("31")) {
									CurrentStockVal = Double
											.parseDouble(StrCurrentStock);
									/*
									 * Log.v(TAG, "QOH UPDATE:" +
									 * CurrentStockVal + "+" + RefNoItemQty);
									 */
									CurrentStockVal = CurrentStockVal
											+ RefNoItemQty;
									String PrintCurrentStockVal = Double
											.toString(CurrentStockVal);
									valueUpdateCurStock.put("QOH",
											PrintCurrentStockVal);
									valueUpdateCurStock.put("syncRec", "0");
									mydb.update(ITEM_LOC_DETAILS,
											valueUpdateCurStock, "RecordId ='"
													+ StrCurRecordId + "'",
											null);
								}

							}
						} else {
							Log.v(TAG, "QOH UPDATE ERROR");
						}
					}
					// =======================================================
				}
			}
		}
		curUpdateItemLocBalQty.close();
		curUpdateBalQty.close();
		mydb.close();

	}

	// Update fItemLocDetails On Cancel Invoice

	private void UpdateStockQuantityOnCancel() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****UpdateStockQuantityOnCancel*****");
		String RefNoCode = etdminvno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUpdateBalQty = null;

		try {
			curUpdateBalQty = mydb.query(INV_DETAILS, null, "RefNo='"
					+ RefNoCode + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (curUpdateBalQty != null) {
			if (curUpdateBalQty.getCount() > 0) {
				while (curUpdateBalQty.moveToNext()) {
					String StrRefNoItemTxn = curUpdateBalQty.getString(3);
					String RefNoItemCode = curUpdateBalQty.getString(5);
					String StrRefNoItemQty = curUpdateBalQty.getString(15);

					RefNoItemQty = Double.parseDouble(StrRefNoItemQty);
					Cursor curUpdateItemLocBalQty = null;
					try {
						curUpdateItemLocBalQty = mydb
								.query(ITEM_LOC_DETAILS, null, "Itemcode='"
										+ RefNoItemCode + "' AND LocCode='"
										+ UserLocCode + "'", null, null, null,
										null);
					} catch (Exception e) {
					}

					if (curUpdateItemLocBalQty != null) {
						if (curUpdateItemLocBalQty.getCount() > 0) {
							while (curUpdateItemLocBalQty.moveToNext()) {
								ContentValues valueUpdateCurStock = new ContentValues();
								String StrCurrentStock = curUpdateItemLocBalQty
										.getString(3);
								String StrCurRecordId = curUpdateItemLocBalQty
										.getString(4);
								if (StrRefNoItemTxn.equals("22")
										|| StrRefNoItemTxn.equals("27")) {
									CurrentStockVal = Double
											.parseDouble(StrCurrentStock);
									/*
									 * Log.v(TAG, "QOH UPDATE:" +
									 * CurrentStockVal + "+" + RefNoItemQty);
									 */
									CurrentStockVal = CurrentStockVal
											+ RefNoItemQty;
									String PrintCurrentStockVal = Double
											.toString(CurrentStockVal);
									valueUpdateCurStock.put("QOH",
											PrintCurrentStockVal);
									valueUpdateCurStock.put("syncRec", "0");
									mydb.update(ITEM_LOC_DETAILS,
											valueUpdateCurStock, "RecordId ='"
													+ StrCurRecordId + "'",
											null);
								} else if (StrRefNoItemTxn.equals("25")
										|| StrRefNoItemTxn.equals("31")) {
									CurrentStockVal = Double
											.parseDouble(StrCurrentStock);
									/*
									 * Log.v(TAG, "QOH UPDATE:" +
									 * CurrentStockVal + "-" + RefNoItemQty);
									 */
									CurrentStockVal = CurrentStockVal
											- RefNoItemQty;
									String PrintCurrentStockVal = Double
											.toString(CurrentStockVal);
									valueUpdateCurStock.put("QOH",
											PrintCurrentStockVal);
									valueUpdateCurStock.put("syncRec", "0");
									mydb.update(ITEM_LOC_DETAILS,
											valueUpdateCurStock, "RecordId ='"
													+ StrCurRecordId + "'",
											null);
								}

							}
						} else {
							Log.v(TAG, "QOH UPDATE ERROR");
						}
					}
					curUpdateItemLocBalQty.close();
				}
			}
		}
		curUpdateBalQty.close();
		mydb.close();
	}

	// Update current invoice state
	private void updateInvoiceCurrentState() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****updateInvoiceCurrentState*****");
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectLastinvrecup = null;
		String columsup[] = { "tempRepInvSerial" };
		try {
			selectLastinvrecup = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"tempRepInvSerial='" + currentSerial + "'", null, null,
					null, null);
		} catch (Exception e) {
		}

		try {
			if (selectLastinvrecup != null) {
				if (selectLastinvrecup.getCount() > 0) {
					while (selectLastinvrecup.moveToNext()) {
						ContentValues valueupdateInvHead = new ContentValues();
						valueupdateInvHead.put("activeInvCusDiscountValue",
								etdminvdiscount.getText().toString());
						valueupdateInvHead.put("recordDate", etdminvdate
								.getText().toString());
						valueupdateInvHead.put("invoiceComplete", "2");// Invoice
																		// Save
																		// Complete
						valueupdateInvHead.put("activeInvoice", "0");
						valueupdateInvHead.put("invlateststate", "0");
						valueupdateInvHead.put("invoiceRef", etdminvno
								.getText().toString());

						mydb.update(TEMP_REP_INVOICESUMERY, valueupdateInvHead,
								"tempRepInvSerial=" + currentSerial, null);

					}
				} else {

					Toast.makeText(getApplicationContext(),
							"Error in update 1", Toast.LENGTH_SHORT).show();
				}
				selectLastinvrecup.close();
			}

			else {
				Toast.makeText(getApplicationContext(), "Error in update 2",
						Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
		}
		mydb.close();
	}

	// Update current invoice Cancel state
	private void updateInvoiceCancelState() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****updateInvoiceCancelState*****");
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectLastinvrecup = null;
		String columsup[] = { "tempRepInvSerial" };
		try {
			selectLastinvrecup = mydb.query(TEMP_REP_INVOICESUMERY, columsup,
					"tempRepInvSerial='" + currentSerial + "'", null, null,
					null, null);
		} catch (Exception e) {
		}

		try {
			if (selectLastinvrecup != null) {
				if (selectLastinvrecup.getCount() > 0) {
					while (selectLastinvrecup.moveToNext()) {
						ContentValues valueupdateInvHead = new ContentValues();

						valueupdateInvHead.put("invoiceComplete", "5");// Invoice
																		// Save
																		// Complete
						valueupdateInvHead.put("activeInvoice", "0");
						valueupdateInvHead.put("invlateststate", "0");
						mydb.update(TEMP_REP_INVOICESUMERY, valueupdateInvHead,
								"tempRepInvSerial=" + currentSerial, null);
					}
				} else {

					Toast.makeText(getApplicationContext(),
							"Error in update 1", Toast.LENGTH_SHORT).show();
				}

			}

			else {
				Toast.makeText(getApplicationContext(), "Error in update 2",
						Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
		}
		selectLastinvrecup.close();
		mydb.close();
	}

	// Update current invoice Undo state
	private void updateInvoiceUndoState() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****updateInvoiceUndoState*****");
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectLastinvrecupdate = null;
		String columsup[] = { "tempRepInvSerial" };
		try {
			selectLastinvrecupdate = mydb.query(TEMP_REP_INVOICESUMERY,
					columsup, "tempRepInvSerial='" + currentSerial + "'", null,
					null, null, null);
		} catch (Exception e) {
		}

		try {
			if (selectLastinvrecupdate != null) {
				if (selectLastinvrecupdate.getCount() > 0) {
					while (selectLastinvrecupdate.moveToNext()) {
						ContentValues valueupdateInvHeadUpdate = new ContentValues();
						valueupdateInvHeadUpdate.put("invoiceComplete", "0");// Invoice
																				// Save
																				// Complete
						valueupdateInvHeadUpdate.put("activeInvoice", "1");
						valueupdateInvHeadUpdate.put("activeInvoiceValue", "0");
						valueupdateInvHeadUpdate.put("activeInvItemDiscount",
								"0");
						valueupdateInvHeadUpdate.put("activeInvCusDiscount",
								"0");
						valueupdateInvHeadUpdate.put(
								"activeInvCusDiscountValue", "0");
						valueupdateInvHeadUpdate
								.put("InvoiceCustomerCode", "0");
						valueupdateInvHeadUpdate.put("InvoiceCustomerName", "");
						valueupdateInvHeadUpdate.put("InvoiceSynchState", "0");
						valueupdateInvHeadUpdate.put("recordDate",
								getCurrentTimeStringCustom());
						valueupdateInvHeadUpdate.put("recordSynchDate", "0");
						valueupdateInvHeadUpdate.put("invlateststate", "9");
						valueupdateInvHeadUpdate.put(
								"activeInvoiceReturnValue", "0");
						valueupdateInvHeadUpdate.put("activeInvoiceRemarks",
								" ");
						valueupdateInvHeadUpdate.put("invoiceNoOfItems", "0");
						valueupdateInvHeadUpdate.put("invoiceRefStl", "");
						mydb.update(TEMP_REP_INVOICESUMERY,
								valueupdateInvHeadUpdate, "tempRepInvSerial="
										+ currentSerial, null);

					}
				} else {

					Toast.makeText(getApplicationContext(),
							"Error in update 1", Toast.LENGTH_SHORT).show();
				}
				selectLastinvrecupdate.close();
			}

			else {
				Toast.makeText(getApplicationContext(), "Error in update 2",
						Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
		}
		mydb.close();
		// Delete records from invoice items details
		deleteUndoInvoiceItems();
	}

	private void deleteUndoInvoiceItems() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor undoinvitemslist = null;
		String columsup[] = { "refInvoiceDetNo" };
		try {
			undoinvitemslist = mydb.query(INV_DETAILS, columsup,
					"refInvoiceDetNo='" + currentSerial + "'", null, null,
					null, null);
		} catch (Exception e) {
		}

		if (undoinvitemslist != null) {
			if (undoinvitemslist.getCount() > 0) {
				while (undoinvitemslist.moveToNext()) {
					mydb.delete(INV_DETAILS, "refInvoiceDetNo ='"
							+ currentSerial + "'", null);
				}
			}
		}
		undoinvitemslist.close();
		mydb.close();
	}

	// Once complete current invoice will generate new invoice
	private void addNewInvoice() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "****addNewInvoice SI****");
		int preInvoiceNo = Integer.parseInt(currentSerial);
		int newInvoiceNo = preInvoiceNo + 1;
		LatestInvNumber = String.valueOf(newInvoiceNo);
		ActiveInvoice = "1";
		RepInvCode = TransTypePrefix.trim() + AgentPrefixType.trim()
				+ currentUserPrefix;
		/*
		 * Log.v(TAG, "RepInvCode :" + TransTypePrefix + "|" + AgentPrefixType +
		 * "|" + currentUserPrefix);
		 */
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		try {
			ContentValues saveTempuserinvoice = new ContentValues();
			saveTempuserinvoice.put("repusername", currentUserTemp);
			saveTempuserinvoice.put("repprefix", currentUserPrefix);
			saveTempuserinvoice.put("tempRepInvNoCode", RepInvCode);
			saveTempuserinvoice.put("tempRepInvSerial", LatestInvNumber);
			saveTempuserinvoice.put("invoiceComplete", "0");
			saveTempuserinvoice.put("activeInvoice", ActiveInvoice);
			saveTempuserinvoice.put("activeInvoiceValue", "0");
			saveTempuserinvoice.put("activeInvItemDiscount", "0");
			saveTempuserinvoice.put("activeInvCusDiscount", "0");
			saveTempuserinvoice.put("activeInvCusDiscountValue", "0");
			saveTempuserinvoice.put("InvoiceCustomerCode", "0");
			saveTempuserinvoice.put("InvoiceCustomerName", "");
			saveTempuserinvoice.put("InvoiceSynchState", "0");
			saveTempuserinvoice.put("recordDate", getCurrentTimeStringCustom());
			saveTempuserinvoice.put("recordSynchDate", "0");
			saveTempuserinvoice.put("invlateststate", "9");
			saveTempuserinvoice.put("activeInvoiceReturnValue", "0");
			saveTempuserinvoice.put("activeInvoiceRemarks", "");
			saveTempuserinvoice.put("invoiceNoOfItems", "0");
			saveTempuserinvoice.put("invoiceRef", "0");
			saveTempuserinvoice.put("invoiceRefStl", "");

			mydb.insert(TEMP_REP_INVOICESUMERY, null, saveTempuserinvoice);
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured C..",
					Toast.LENGTH_SHORT).show();
		}
		updateFcompanyBranch();
		mydb.close();
	}

	private void updateFcompanyBranch() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectUserSerial = null;

		try {
			selectUserSerial = mydb.query(INV_COMPANY_BRANCH, null,
					"cSettingsCode='SECINV' AND BranchCode='" + currentUserTemp
							+ "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (selectUserSerial != null) {
			if (selectUserSerial.getCount() > 0) {
				if (selectUserSerial.moveToLast()) {
					ContentValues updateNewSerial = new ContentValues();
					String serialStId = selectUserSerial.getString(0);
					updateNewSerial.put("nNumVal", LatestInvNumber);
					mydb.update(INV_COMPANY_BRANCH, updateNewSerial,
							"fcombra_id ='" + serialStId + "'", null);
				}
			}
		}

	}

	protected void latestInvoiceRecord() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****latestInvoiceRecord*****");
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String[] resultserial = { "tempRepInvSerial" };
		Cursor selectLastinvrec = null;
		try {
			selectLastinvrec = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"repusername='" + currentUserTemp
							+ "' AND invlateststate='9'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (selectLastinvrec != null) {
			if (selectLastinvrec.getCount() > 0) {
				if (selectLastinvrec.moveToLast()) {
					currentSerial = selectLastinvrec.getString(4);
					LatestInvState = selectLastinvrec.getString(5); // If
																	// invoice
																	// complete
					if (LatestInvState.equals(2)) {
						// saveTempuserDeails();
					} else {
					}

				}
			} else {
				LatestInvNumber = "1";
				LatestInvState = "0";
				ActiveInvoice = "1";
				addNewInvoice();
			}

		} else {
			LatestInvNumber = "1";
			LatestInvState = "0";
			ActiveInvoice = "1";
			addNewInvoice();
		}
		selectLastinvrec.close();
		mydb.close();
	}

	protected void agentPrefix() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectAgentPreType = null;

		try {
			selectAgentPreType = mydb.query(ITEM_CONTROL, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectAgentPreType != null) {
			if (selectAgentPreType.getCount() > 0) {
				while (selectAgentPreType.moveToNext()) {
					AgentPrefixType = selectAgentPreType.getString(18);
				}
			}
		}
		selectAgentPreType.close();
		mydb.close();
		return;
	}

	protected void invoiceTransType() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectTransType = null;

		try {
			selectTransType = mydb.query(ITEM_COMPANY_SETTING, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (selectTransType != null) {
			if (selectTransType.getCount() > 0) {
				while (selectTransType.moveToNext()) {
					String cSettingsCode = selectTransType.getString(1);
					String cCharValue = selectTransType.getString(4);
					if (cSettingsCode.equals("SECINV")) {
						TransTypePrefix = cCharValue.trim();
					}

				}
			}
		}
		selectTransType.close();
		mydb.close();
		return;
	}

	// Print Account Description
	public void AddCustomerDetails(View view) {
		customerReloadTag = 202;
		etdminvno.setText("");
		Button des = (Button) view;
		String SetTransactionDesc = des.getText().toString();
		invcuscode = SetTransactionDesc.trim();
		viewDebtorDetails();
		ListViewShowCustomers.setVisibility(view.GONE);
		ListViewInvHeaderButton.setVisibility(view.VISIBLE);
		ListViewInvHeaderDetails.setVisibility(view.VISIBLE);
	}

	private void viewDebtorDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowCusDet = null;
		try {
			allrowCusDet = mydb.query(ITEM_DEBTOR, null, "DebCode='"
					+ invcuscode + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (allrowCusDet != null) {
			if (allrowCusDet.getCount() > 0) {
				while (allrowCusDet.moveToNext()) {
					etdminvcusdis.setEnabled(true);
					invcuscode = allrowCusDet.getString(1);
					invcusname = allrowCusDet.getString(2);
					invcusdiscount = allrowCusDet.getString(10);
					etdminvcustomer.setText(invcusname);
					etdminvcusdis.setText(invcusdiscount);
				}
			}
		}
	}

	public void AddLocationItemsDetails(View view) {
		Button des = (Button) view;
		refNoSummaryInvoice = des.getText().toString();
		viewInvoiceSummary();
		ListInvTag = 99;
		ListViewselectinvoices.setVisibility(view.GONE);
		ListViewInvHeaderButton.setVisibility(view.VISIBLE);
		ListViewInvHeaderDetails.setVisibility(view.VISIBLE);

	}

	// ****View Stock Order Number Details******
	public void AddStockOrdersDetailsf(View view) {
		Button des = (Button) view;
		refNoStockOrderInvoice = des.getText().toString();
		INVSelectItems.setEnabled(true);
		removepreDetails();
		updateStOrdNoUserSummary();
		viewStockOrderInvoiceSummary();
		// ListInvTag = 99;
		ListViewselectstockorders.setVisibility(view.GONE);
		ListViewInvHeaderButton.setVisibility(view.VISIBLE);
		ListViewInvHeaderDetails.setVisibility(view.VISIBLE);

	}

	private void removepreDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			mydb.delete(INV_DETAILS, "refInvStockOrderNo ='"
					+ refNoStockOrderInvoice + "'", null);
		} catch (Exception e) {
		}
		mydb.close();
	}

	private void updateStOrdNoUserSummary() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****updateStOrdNoUserSummary*****");
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor updateStOrdRef = null;
		try {
			updateStOrdRef = mydb.query(USER_SETTINGS, null, "username='"
					+ currentUserTemp + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (updateStOrdRef != null) {
			if (updateStOrdRef.getCount() > 0) {
				while (updateStOrdRef.moveToNext()) {
					currentStRefNoUser = updateStOrdRef.getString(4);
					if (currentStRefNoUser.equals("0")) {
						ContentValues valueupdate = new ContentValues();
						valueupdate.put("currentStOrdNo",
								refNoStockOrderInvoice);
						mydb.update(USER_SETTINGS, valueupdate, "username ='"
								+ currentUserTemp + "'", null);
					} /*
					 * else { //deleteAvailableItems();// Delete Previous Items
					 * }
					 */

				}
			}

		}
		updateStOrdRef.close();
		mydb.close();
	}

	private void viewStockOrderInvoiceSummary() {
		// Log.v(TAG, "*******viewStockOrderInvoiceSummary*******");
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String columssto[] = { "RefNo" };
		String DebName = null;
		Cursor allrowstoinvsum = null;
		Cursor allrowstoinvdebtor = null;
		try {
			allrowstoinvsum = mydb.query(STOCK_ORDER_HEAD, null, "RefNo='"
					+ refNoStockOrderInvoice + "' AND stOrderComplete='0'",
					null, null, null, null);

		} catch (Exception e) {
		}
		if (allrowstoinvsum != null) {
			if (allrowstoinvsum.getCount() > 0) {
				while (allrowstoinvsum.moveToNext()) {

					String DebCode = allrowstoinvsum.getString(8);
					String InvDis = allrowstoinvsum.getString(10);
					String ManuRefNo = allrowstoinvsum.getString(13);
					String OutDis = allrowstoinvsum.getString(14);
					String Remarks = allrowstoinvsum.getString(17);
					String TotMkrAmt = allrowstoinvsum.getString(20);
					String TotalAmt = allrowstoinvsum.getString(21);
					String TotalDis = allrowstoinvsum.getString(22);
					String TxnDate = allrowstoinvsum.getString(27);
					String OutDisVal = allrowstoinvsum.getString(30);
					invDiliveryDate = allrowstoinvsum.getString(32);
					// StrManualDiscount > StrMainInvValTot
					try {
						allrowstoinvdebtor = mydb.query(ITEM_DEBTOR, null,
								"DebCode='" + DebCode + "'", null, null, null,
								null);
					} catch (Exception e) {
					}
					if (allrowstoinvdebtor != null) {
						if (allrowstoinvdebtor.getCount() > 0) {
							while (allrowstoinvdebtor.moveToNext()) {
								DebName = allrowstoinvdebtor.getString(2);
							}
						}
					}
					double TotalAmtVal = Double.parseDouble(TotalAmt
							.replaceAll("[,]", ""));
					StrMainInvValTot = TotalAmtVal;
					String TotalAmtDis = formatValues.format(TotalAmtVal);

					etdminvno.setText("");
					etdmstorderno.setText(refNoStockOrderInvoice);
					etdminvdate.setText(invDiliveryDate);
					etdminvcustomer.setText(DebName);
					etdminvremarks.setText(Remarks);
					etdminvcusdis.setText(OutDis);
					etdminvCusdiscount.setText(OutDisVal);
					double InvDisVal = Double.parseDouble(InvDis.replaceAll(
							"[,]", ""));
					String InvDisValDis = formatValues.format(InvDisVal);
					etdminvdiscount.setText(InvDisValDis);

					double TotMkrAmtVal = Double.parseDouble(TotMkrAmt
							.replaceAll("[,]", ""));
					String TotMkrAmtDis = formatValues.format(TotMkrAmtVal);
					marketretval.setText(TotMkrAmtDis);

					double TotalDisVal = Double.parseDouble(TotalDis
							.replaceAll("[,]", ""));
					StrMainLineDisValTot = TotalDisVal;
					String TotalDisValDis = formatValues.format(TotalDisVal);
					invoicedisval.setText(TotalDisValDis);

					invoicetotval.setText(TotalAmtDis);
					INVSelectCustomer.setEnabled(false);
					allrowstoinvsum.close();
				}
			} else {
				Toast.makeText(getApplicationContext(), "Filter Error:",
						Toast.LENGTH_SHORT).show();
			}
		}
		allrowstoinvsum.close();
		mydb.close();
	}

	private void viewInvoiceSummary() {
		// Log.v(TAG, "*******viewInvoiceSummary*******");
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowinvsum = null;
		try {
			String query = "SELECT INS.invoiceRef,INS.recordDate,INS.InvoiceCustomerName,IH.TotMkrAmt,INS.tempRepInvSerial,INS.activeInvoiceRemarks,IH.RefNo,IH.RefNo1,IH.InvAmt,IH.TotalDis,IH.OutDis,IH.outDisVal,INS.activeInvCusDiscount,INS.activeInvCusDiscountValue,INS.activeInvItemDiscount FROM frepInvoiceSumery INS,FinvHed IH WHERE INS.invoiceRef = IH.RefNo AND IH.RefNo ='"
					+ refNoSummaryInvoice + "'";
			allrowinvsum = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (allrowinvsum != null) {
			if (allrowinvsum.getCount() > 0) {
				while (allrowinvsum.moveToNext()) {
					etdminvcusdis.setEnabled(false);
					etdminvCusdiscount.setEnabled(false);
					currentSerial = allrowinvsum.getString(4);
					String SumRefNumber = allrowinvsum.getString(6);
					String SumSalesOrderRefNo = allrowinvsum.getString(7);
					String SumInvoiceDate = allrowinvsum.getString(1);
					String SumCustomerName = allrowinvsum.getString(2);
					String SumRemarks = allrowinvsum.getString(5);
					String SumCustomerDisRate = allrowinvsum.getString(10);
					String SumCusDisVal = allrowinvsum.getString(11);
					String SumMarketRet = allrowinvsum.getString(3);
					String SumTotDiscount = allrowinvsum.getString(9);
					String SumTotValue = allrowinvsum.getString(8);
					String SumInvCusDiscount = allrowinvsum.getString(12);
					String SumInvCusDiscountValue = allrowinvsum.getString(13);
					String activeInvItemDiscount = allrowinvsum.getString(14);

					double TotalAmtValSum = Double.parseDouble(SumTotValue
							.replaceAll("[,]", ""));
					StrMainInvValTot = TotalAmtValSum;
					StrMainLineDisValTot = Double
							.parseDouble(activeInvItemDiscount.replaceAll(
									"[,]", ""));
					etdminvcusdis.setText(SumCustomerDisRate);
					etdminvCusdiscount.setText(SumCusDisVal);
					activeInvItemDiscount = formatValues
							.format(StrMainLineDisValTot);
					invoicedisval.setText(activeInvItemDiscount);
					invoicetotval.setText(SumTotValue);
					// Log.v(TAG, "CUS DIS VAL :" + SumInvCusDiscountValue);
					etdminvno.setText(refNoSummaryInvoice);
					etdmstorderno.setText(SumSalesOrderRefNo);
					etdminvdate.setText(SumInvoiceDate);
					etdminvcustomer.setText(SumCustomerName);
					etdminvremarks.setText(SumRemarks);
					marketretval.setText(SumMarketRet);

					INVPrint.setEnabled(true);
					INVPrint.setClickable(true);
					INVSelectCustomer.setEnabled(false);
					INVSelectItems.setEnabled(false);
					// janasss
				}
			}
		}
		allrowinvsum.close();
		mydb.close();
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_invoice_new);

		Bundle bundle = getIntent().getExtras();
		TagId = bundle.getString("TAGID");

		dbHelperCustomer = new DM_CustomerList_Adapter(this);
		dbHelperCustomer.open();

		etdminvno = (Button) findViewById(R.id.etdminvno);
		etdmstorderno = (Button) findViewById(R.id.etdmstorderno);
		etdminvdate = (EditText) findViewById(R.id.etdminvdate);
		etdminvcustomer = (EditText) findViewById(R.id.etdminvcustomer);
		etdminvremarks = (EditText) findViewById(R.id.etdminvremarks);
		etdminvcusdis = (EditText) findViewById(R.id.etdminvcusdis);
		etdminvcusdis.addTextChangedListener(calculateCustomerInvDiscount);
		etdminvcusdis
				.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(2) });
		etdminvCusdiscount = (EditText) findViewById(R.id.etdminvCusdiscount);
		etdminvCusdiscount.addTextChangedListener(calculateCusInvDisManuVal);
		etdminvCusdiscount
				.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(2) });
		etdminvdiscount = (EditText) findViewById(R.id.etdminvdiscount);
		dminvfiltercustomer = (EditText) findViewById(R.id.dminvfiltercustomer);
		marketretval = (EditText) findViewById(R.id.marketretval);
		invoicedisval = (EditText) findViewById(R.id.invoicedisval);
		invoicetotval = (EditText) findViewById(R.id.invoicetotval);
		myFilterCustomer = (EditText) findViewById(R.id.dminvfiltercustomer);

		INVSelectCustomer = (Button) findViewById(R.id.btninvselectcustomer);
		INVSelectItems = (Button) findViewById(R.id.btninvdetails);
		INVSave = (Button) findViewById(R.id.account_saveButton);
		INVPrint = (Button) findViewById(R.id.account_printButton);
		INVCancel = (Button) findViewById(R.id.account_cancelButton);
		INVUndo = (Button) findViewById(R.id.account_undoButton);
		CusListAllViewBtn = (Button) findViewById(R.id.cuslistallviewBtn);

		ListViewShowCustomers = (LinearLayout) findViewById(R.id.dminvoiceselectcus);
		ListViewInvHeaderButton = (LinearLayout) findViewById(R.id.invheaderbuttons);
		ListViewInvHeaderDetails = (LinearLayout) findViewById(R.id.dminvoiceheadersection);
		ListViewselectinvoices = (LinearLayout) findViewById(R.id.dminvoiceselectinvoices);
		ListViewselectstockorders = (LinearLayout) findViewById(R.id.dmselectstockorders);
		dminvfiltercustomer = (EditText) findViewById(R.id.dminvfiltercustomer);
		customerSearchBox = (RelativeLayout) findViewById(R.id.customerSearchBox);
		etdminvdate.setText(getCurrentTimeStringCustom());

		if (TagId.equals("5")) {
			etdmstorderno.setEnabled(false);

		}

		currentuserTemp();
		updateCurrentSoSumary();
		invoiceTransType();
		agentPrefix();
		// populateCustomerList();
		checkLatestInvoiceSerial();// Check latest Reference Serial
		checkInvoiceSummary();

		CusListAllViewBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				customerSearchBox.setVisibility(view.VISIBLE);
				customerReloadTag = 404;
				populateCustomerDetailsList();
			}

		});

		// Invoice heder popup menu list
		popup_invmenubut = (Button) findViewById(R.id.dmpopupmenulist);
		popup_invmenubut.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(final View v) {
				// TODO Auto-generated method stub
				PopupMenu popup = new PopupMenu(DM_InvoiceNew.this,
						popup_invmenubut);
				popup.getMenuInflater().inflate(R.menu.dm_popup_invmenu,
						popup.getMenu());

				popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
					@TargetApi(Build.VERSION_CODES.HONEYCOMB)
					public boolean onMenuItemClick(MenuItem item) {
						//String currentMenuTitle = 
						
						slectedMenuOption = item.getTitle().toString();
						String chkcustomer = etdminvcustomer.getText()
								.toString();
						Log.v(TAG, "chkcustomer:" + slectedMenuOption.trim());

						if (etdminvcustomer.length() == 0) {
							final AlertDialog alertDialog = new AlertDialog.Builder(
									DM_InvoiceNew.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("SELECT CUSTOMER");
							// Setting Dialog Message
							alertDialog
									.setMessage("Select Valid Customer First");
							// Setting Icon to Dialog
							alertDialog.setIcon(R.drawable.warning);
							// Setting OK Button
							alertDialog.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											alertDialog.dismiss();
										}
									});
							// Showing Alert Message
							alertDialog.show();
							alertDialog.setCanceledOnTouchOutside(false);

						} else {
							if(slectedMenuOption.equals("Last Three Visit")){
								displayLastThreeVisit(v);
							}
							else{
								displayCustomerOutstand(v);
								
							}
							Log.v(TAG, "VISIT 3 CALL");
						}
						return true;
					}

					private void displayCustomerOutstand(View v) {
						// TODO Auto-generated method stub
						
						Intent myIntent = new Intent(v.getContext(),
								DM_RetOutstanding_Information.class);
						myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
								| Intent.FLAG_ACTIVITY_NEW_TASK);
						myIntent.putExtra("TAGID", "SI/"+invcuscode);
						startActivityForResult(myIntent, 0);
						finish();
					}

					private void displayLastThreeVisit(View v) {
						Log.v(TAG, "VISIT 3 CALL METHOD");
						// TODO Auto-generated method stub
						Intent myIntent = new Intent(v.getContext(),
								DM_Customer_Last_Three_Visit.class);
						myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
								| Intent.FLAG_ACTIVITY_NEW_TASK);
						myIntent.putExtra("REPORTNAME", slectedMenuOption + "/"
								+ invcuscode);
						startActivityForResult(myIntent, 0);
						finish();
					}
				});

				popup.show();
			}
		});

		// Button touchup Event handling
		etdminvno.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View view, MotionEvent motionevent) {
				int action = motionevent.getAction();
				if (action == MotionEvent.ACTION_DOWN) {
					// INVPrint.setEnabled(true);
				} else if (action == MotionEvent.ACTION_UP) {
					ListViewselectinvoices.setVisibility(view.VISIBLE);
					ListViewInvHeaderButton.setVisibility(view.GONE);
					ListViewInvHeaderDetails.setVisibility(view.GONE);
					// INVPrint.setEnabled(true);
					TEXTCHANGEACTIVE = 44;
					ShowInvoiceList();
					// jana
				}
				return false;
			}

		});

		// ******View Avilable Sales Oreder Numbers********
		etdmstorderno.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View view, MotionEvent motionevent) {
				int action = motionevent.getAction();
				if (action == MotionEvent.ACTION_DOWN) {
					/*
					 * Toast.makeText(getApplicationContext(),
					 * "Button ACTION_DOWN", Toast.LENGTH_SHORT).show();
					 */
				} else if (action == MotionEvent.ACTION_UP) {
					ListViewselectstockorders.setVisibility(view.VISIBLE);
					ListViewInvHeaderButton.setVisibility(view.GONE);
					ListViewInvHeaderDetails.setVisibility(view.GONE);
					ShowStockOrdersList();
				}
				return false;
			}

		});

		INVSelectCustomer.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				myFilterCustomer.setText("");
				myFilterCustomer.requestFocus();
				customerSearchBox.setVisibility(view.GONE);
				customerReloadTag = 202;
				populateCustomerList();
				ListViewShowCustomers.setVisibility(view.VISIBLE);
				ListViewInvHeaderButton.setVisibility(view.GONE);
				ListViewInvHeaderDetails.setVisibility(view.GONE);

			}

		});

		// Display Invoice Items Details
		INVSelectItems.setOnClickListener(new View.OnClickListener() {
			public void onClick(final View view) {
				if (etdmstorderno.length() != 0) {
					// Sales Order Details View Page Directing
					mapStockLoadingChecking();
				}

				else {
					if (etdminvcustomer.length() == 0
							|| etdminvdate.length() == 0) {
						try {
							showDialog(DIALOG_SELECT_CUSTOMER);
						} catch (Exception ex) {
							ex.printStackTrace();
						}
						return;
					} else {
						updateInvoiceSumTable();
						Intent myIntent = new Intent(view.getContext(),
								DM_InvoiceDetails.class);
						myIntent.putExtra("TAGID", "4");
						startActivityForResult(myIntent, 0);
					}
				}
			}
		});

	}

	// 20140131
	private void updateCurrentSoSumary() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor updateTxnDate = null;
		try {
			updateTxnDate = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"repusername='" + currentUserTemp
							+ "' AND invlateststate='9'", null, null, null,
					null);
		} catch (Exception e) {
		}

		try {
			if (updateTxnDate != null) {
				if (updateTxnDate.getCount() > 0) {
					while (updateTxnDate.moveToNext()) {
						ContentValues valueupdateInvHeadUpdateSum = new ContentValues();
						valueupdateInvHeadUpdateSum.put("recordDate",
								getCurrentTimeStringCustom());
						mydb.update(TEMP_REP_INVOICESUMERY,
								valueupdateInvHeadUpdateSum, "repusername='"
										+ currentUserTemp
										+ "' AND invlateststate='9'", null);
					}
				}
			}
		} catch (Exception e) {
		}
		updateTxnDate.close();
		mydb.close();
		return;
	}

	// Check Sales Order Used For Invoicing
	// Step 01 = SalesOrder Convertion Method 01
	protected void mapStockLoadingChecking() {
		// TODO Auto-generated method stub
		String StockOrderRefHed = etdmstorderno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curStLoadSumCkState = null;
		try {
			curStLoadSumCkState = mydb.query(STOCK_ORDER_HEAD, null, "RefNo='"
					+ refNoStockOrderInvoice + "' AND stOrderComplete='0'",
					null, null, null, null);

		} catch (Exception e) {
		}
		if (curStLoadSumCkState != null) {
			if (curStLoadSumCkState.getCount() > 0) {
				// Log.v(TAG, "Active Stock Order" + StockOrderRefHed);
				checkStocksItemsAvailability();
			} else {
				// Log.v(TAG, "Inactive Stock Order");
				if (etdmstorderno.length() != 0 && etdminvno.length() != 0) {
					updateInvoiceSumTable();
					Intent myIntent = new Intent(this, DM_InvoiceDetails.class);
					myIntent.putExtra("TAGID", "4");
					startActivityForResult(myIntent, 0);
				}
			}
		}
	}

	// Step 02 = SalesOrder Convertion Method 02
	private void checkStocksItemsAvailability() {
		// TODO Auto-generated method stub
		String StockOrderRef = etdmstorderno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// Check Sales Order Items Quantity with Sales Rep Location Quantities
		Cursor CheckStockAvailable = null;
		String checkQuery = "SELECT FO.Qty,FO.Itemcode,FO.RefNo,FO.Type,FIL.ItemCode,FIL.LocCode,FIL.QOH,FI.ItemCode,FI.ItemName FROM FOrddet FO,fItemLoc FIL,fItems FI Where FO.Itemcode = FIL.ItemCode AND FI.ItemCode = FO.Itemcode AND RefNo ='"
				+ StockOrderRef
				+ "' AND FIL.LocCode ='"
				+ UserLocCode
				+ "' group by FO.Itemcode,FO.Type";
		CheckStockAvailable = mydb.rawQuery(checkQuery, null);

		if (CheckStockAvailable != null) {
			if (CheckStockAvailable.getCount() > 0) {
				int arrayChkItem = 0;
				while (CheckStockAvailable.moveToNext()) {

					String QtyStr = CheckStockAvailable.getString(0);
					String ItemcodeStr = CheckStockAvailable.getString(1);
					String RefNoStr = CheckStockAvailable.getString(2);
					String TypeStr = CheckStockAvailable.getString(3);
					String QOHStr = CheckStockAvailable.getString(6);
					// Log.v(TAG, "Item Code DJ:" + ItemcodeStr
					// +"=:"+QtyStr+"=:"+QOHStr);
					// Sales order total Quantity
					Double QtyStrDouVal = Double.parseDouble(QtyStr);
					int QtyStrVal = Integer.valueOf(QtyStrDouVal.intValue());
					// int QtyStrVal = Integer.parseInt(QtyStr);
					// Total Quantity on Stocks
					Double QOHStrDouVal = Double.parseDouble(QOHStr);
					int QOHStrVal = Integer.valueOf(QOHStrDouVal.intValue());
					// Check Quantity Validate with Stocks Quantity

					if (QOHStrVal < QtyStrVal) {
						if (TypeStr.equals("SA") || TypeStr.equals("FI")) {
							SONULLCHECKED = 33;
							// stringArray= new
							// String[CheckStockAvailable.getCount()];
							if (QOHStrVal == 0) {
								String printString = ItemcodeStr + "  QOH =:"
										+ QOHStr;
								// Log.v(TAG, "printString QOH:" + arrayChkItem
								// + ")" + printString);
								stringArray = stringArray + printString + "\n";
								arrayChkItem++;
							} else if (QOHStrVal != 0) {
								String printString = ItemcodeStr
										+ " Adjust QTY =:" + QOHStr;
								// Log.v(TAG, "printString Adjust QTY:" +
								// arrayChkItem + ")" + printString);
								stringArray = stringArray + printString + "\n";
								arrayChkItem++;
							}
						}
					}
				}
			} else {
				Log.v(TAG, "Error");
			}
		}

		// Check Stocks Quantity Adjusted
		if (SONULLCHECKED == 0) {
			// Log.v(TAG, "Sales Order Details Able to Map");
			mapStLoadItemsInvoice();
		} else if (SONULLCHECKED == 33) {
			displayAlertDialog();
		}
	}

	private void mapStLoadItemsInvoice() {
		// TODO Auto-generated method stub
		currentInvoiceNo();
		String StockOrderRef = etdmstorderno.getText().toString();
		String itemname = null, itemsincase = null, itemcode = null;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curstlitemheader = null;
		Cursor curstlitem = null;
		Cursor curselectitemdet = null;

		try {
			curstlitemheader = mydb.query(STOCK_ORDER_HEAD, null, "RefNo='"
					+ StockOrderRef + "'", null, null, null, null);

		} catch (Exception e) {
		}
		if (curstlitemheader != null) {
			if (curstlitemheader.getCount() > 0) {
				while (curstlitemheader.moveToNext()) {
					mainDelvDate = curstlitemheader.getString(32);
				}
			}
		}

		try {
			curstlitem = mydb.query(STOCK_ORDER_DETAIL, null, "RefNo='"
					+ StockOrderRef + "'", null, null, null, null);

		} catch (Exception e) {
		}

		if (curstlitem != null) {
			if (curstlitem.getCount() > 0) {
				while (curstlitem.moveToNext()) {
					ContentValues newrowfItemsConVal = new ContentValues();
					String Amt = curstlitem.getString(1);
					String BAmt = curstlitem.getString(2);
					String BDisAmt = curstlitem.getString(3);
					String BSellPrice = curstlitem.getString(4);
					String BTSellPrice = curstlitem.getString(5);
					String BTaxAmt = curstlitem.getString(6);
					String BalQty = curstlitem.getString(7);
					String CaseQty = curstlitem.getString(8);
					String CostPrice = curstlitem.getString(9);
					String DisAmt = curstlitem.getString(10);
					String DisPer = curstlitem.getString(11);
					currentItemCode = curstlitem.getString(12);
					String PiceQty = curstlitem.getString(13);
					String Qty = curstlitem.getString(14);
					String ReaCode = curstlitem.getString(15);
					String RecordId = curstlitem.getString(16);
					String RefNo = curstlitem.getString(17);
					String SellPrice = curstlitem.getString(18);
					String SeqNo = curstlitem.getString(19);
					String TSellPrice = curstlitem.getString(20);
					String TaxAmt = curstlitem.getString(21);
					String TxnType = curstlitem.getString(22);
					String Txnseqno = curstlitem.getString(23);
					ItmTxnType = curstlitem.getString(24);
					String TxnDate = curstlitem.getString(25);
					String ItemDisPer = curstlitem.getString(27);
					String ItemDisPerVal = curstlitem.getString(28);
					String ReasonDescRec = curstlitem.getString(29);
					UnitPrice = curstlitem.getString(31);
					Log.v(TAG, "UnitPrice xxxx:" + UnitPrice);
					checkItemAvailability();
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					// ---Get Current ItemsDetails------
					try {
						curselectitemdet = mydb
								.query(ITEMS, null, "ItemCode='"
										+ currentItemCode + "'", null, null,
										null, null);
					} catch (Exception e) {
					}
					if (curselectitemdet != null) {
						if (curselectitemdet.getCount() > 0) {
							while (curselectitemdet.moveToNext()) {
								String itemskucode = curselectitemdet
										.getString(1);
								itemcode = curselectitemdet.getString(2);
								itemname = curselectitemdet.getString(4);
								itemsincase = curselectitemdet.getString(28);
							}
						}
					}
					// Insert Data in to Invoice Details Table
					newrowfItemsConVal.put("Amt", Amt.trim());
					if (ItmTxnType.equals("SA") || ItmTxnType.equals("FI")) {
						double RecheckInvVal = Double.parseDouble(Amt
								.replaceAll("[,]", ""));
						RecheckInvoiceValue = RecheckInvoiceValue
								+ RecheckInvVal;
					} else if (ItmTxnType.equals("UR")
							|| ItmTxnType.equals("MR")) {
						double RecheckRetInvVal = Double.parseDouble(Amt
								.replaceAll("[,]", ""));
						RecheckInvoiceValReturn = RecheckInvoiceValReturn
								+ RecheckRetInvVal;
					}
					newrowfItemsConVal.put("BAmt", BAmt.trim());
					newrowfItemsConVal.put("BDisAmt", BDisAmt.trim());
					newrowfItemsConVal.put("BSellPrice", BSellPrice.trim());
					newrowfItemsConVal.put("BTSellPrice", BTSellPrice.trim());
					newrowfItemsConVal.put("BTaxAmt", BTaxAmt.trim());
					newrowfItemsConVal.put("BalQty", BalQty.trim());
					newrowfItemsConVal.put("CaseQty", CaseQty.trim());
					newrowfItemsConVal.put("CostPrice", CostPrice.trim());
					newrowfItemsConVal.put("DisAmt", DisAmt.trim());
					double RecheckDisVal = Double.parseDouble(DisAmt
							.replaceAll("[,]", ""));
					RecheckInvoiceDiscount = RecheckInvoiceDiscount
							+ RecheckDisVal;
					newrowfItemsConVal.put("DisPer", DisPer.trim());
					newrowfItemsConVal.put("Itemcode", currentItemCode.trim());
					newrowfItemsConVal.put("PiceQty", PiceQty.trim());
					newrowfItemsConVal.put("Qty", Qty.trim());
					newrowfItemsConVal.put("ReaCode", ReaCode.trim());
					newrowfItemsConVal.put("Linkrec", "0");
					newrowfItemsConVal.put("RecordId", RecordId.trim());
					newrowfItemsConVal.put("RefNo", currentInvoiceTempRefCode);
					newrowfItemsConVal.put("SellPrice", SellPrice.trim());
					newrowfItemsConVal.put("SeqNo", SeqNo.trim());
					newrowfItemsConVal.put("TSellPrice", TSellPrice.trim());
					newrowfItemsConVal.put("TaxAmt", TaxAmt.trim());
					newrowfItemsConVal.put("TxnType", TxnType.trim());
					newrowfItemsConVal.put("Txnseqno", Txnseqno.trim());
					newrowfItemsConVal.put("Type", ItmTxnType.trim());
					newrowfItemsConVal.put("TxnDate", mainDelvDate.trim());
					newrowfItemsConVal.put("itemDescription", itemname);
					newrowfItemsConVal.put("refInvoiceDetNo",
							LatestInvNumberStr);
					newrowfItemsConVal.put("refInvoiceDetCode",
							currentInvoiceTempRefCode);
					newrowfItemsConVal.put("refInvitemCaseQty", itemsincase);
					newrowfItemsConVal.put("refInvStockOrderNo", RefNo.trim());
					newrowfItemsConVal.put("invdetSync", "0");
					newrowfItemsConVal.put("invsysdate",
							getAddDateTimeStringFormat().toString());
					// Item discount percentage
					newrowfItemsConVal.put("itemdisper", ItemDisPer);
					// Item discount percentage calculated value
					newrowfItemsConVal.put("itemdisperval", ItemDisPerVal);
					// reason details ref code
					newrowfItemsConVal.put("reasonCode", ReaCode);
					// reason details description
					newrowfItemsConVal.put("reasonDesc", ReasonDescRec);
					newrowfItemsConVal.put("itemUnitPrice", UnitPrice);
					Log.v(TAG, "UnitPrice xxxx:" + UnitPrice);
					mydb.insert(INV_DETAILS, null, newrowfItemsConVal);
				}
			}
		}
		String InvTotalAmt = formatValues.format(RecheckInvoiceValue);
		String InvTotalAmtRet = formatValues.format(RecheckInvoiceValReturn);
		String InvTotalAmtDis = formatValues.format(RecheckInvoiceDiscount);
		/*
		 * Log.v(TAG, "TOT :" + InvTotalAmt + "+" + InvTotalAmtRet + "-" +
		 * InvTotalAmtDis);
		 */
		UpdateMapInvSummary();
	}

	private void UpdateMapInvSummary() {
		// Log.v(TAG, "****UpdateMapInvSummary****");
		// TODO Auto-generated method stub
		String StockOrderRefHed = etdmstorderno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curStLoadSumUpdate = null;
		try {
			curStLoadSumUpdate = mydb.query(STOCK_ORDER_INVOICESUMERY, null,
					"invoiceRef='" + StockOrderRefHed + "'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (curStLoadSumUpdate != null) {
			if (curStLoadSumUpdate.getCount() > 0) {
				while (curStLoadSumUpdate.moveToNext()) {
					ContentValues valueupdate = new ContentValues();
					String TotalAmt = curStLoadSumUpdate.getString(7);
					String InvDis = curStLoadSumUpdate.getString(8);
					invcuscode = curStLoadSumUpdate.getString(11);
					invcusname = curStLoadSumUpdate.getString(12);
					OutDisSumUpdate = curStLoadSumUpdate.getString(9);
					OutDisValSumUpdate = curStLoadSumUpdate.getString(10);
					String NoofItms = curStLoadSumUpdate.getString(19);
					String TotMkrAmt = curStLoadSumUpdate.getString(17);
					String DeliverDate = curStLoadSumUpdate.getString(22);

					valueupdate.put("InvoiceCustomerCode", invcuscode);// Add
					valueupdate.put("InvoiceCustomerName", invcusname);// Add
					valueupdate.put("activeInvCusDiscount", OutDisSumUpdate);// Add
					valueupdate.put("activeInvCusDiscountValue",
							OutDisValSumUpdate);// Add

					Double finalTotInvoiceValue = RecheckInvoiceValue
							+ RecheckInvoiceValReturn;
					String InvTotalAmt = formatValues
							.format(finalTotInvoiceValue);
					valueupdate.put("activeInvoiceValue", InvTotalAmt);

					String InvTotMkrAmt = formatValues
							.format(RecheckInvoiceValReturn);
					valueupdate.put("activeInvoiceReturnValue", InvTotMkrAmt);

					String InvInvDis = formatValues
							.format(RecheckInvoiceDiscount);
					valueupdate.put("activeInvItemDiscount", InvInvDis);
					valueupdate.put("invoiceComplete", "1");
					valueupdate.put("invoiceNoOfItems", NoofItms);
					valueupdate.put("invoiceRefStl", StockOrderRefHed);
					valueupdate.put("recordDate", DeliverDate);

					mydb.update(TEMP_REP_INVOICESUMERY, valueupdate,
							"tempRepInvSerial ='" + LatestInvNumberStr + "'",
							null);
				}
			}
		}
		curStLoadSumUpdate.close();
		mydb.close();
		callDetails();
	}

	private void callDetails() {
		// TODO Auto-generated method stub
		Intent myIntent = new Intent(this, DM_InvoiceDetails.class);
		myIntent.putExtra("TAGID", "4");
		startActivityForResult(myIntent, 0);
	}

	// Step 03:1 = SalesOrder Convertion Method 03 - 1
	private void displayAlertDialog() {
		// TODO Auto-generated method stub
		AlertDialog.Builder myDialog = new AlertDialog.Builder(
				DM_InvoiceNew.this);
		myDialog.setTitle("ITEMS QUANTITY VALIDATE");
		myDialog.setMessage("Items With Sales Order Stock Quntities Not Available Or Adjusted For Following Items.Do you want to proceed with Invoice..");
		final ListView listview = new ListView(DM_InvoiceNew.this);
		array_sort = new ArrayList<String>(Arrays.asList(stringArray));
		LinearLayout layout = new LinearLayout(DM_InvoiceNew.this);
		layout.setOrientation(LinearLayout.VERTICAL);
		layout.addView(listview);
		myDialog.setView(layout);
		DM_SalesOrder_Alert_Adapter arrayAdapter = new DM_SalesOrder_Alert_Adapter(
				DM_InvoiceNew.this, array_sort);
		listview.setAdapter(arrayAdapter);
		listview.setAdapter(new DM_SalesOrder_Alert_Adapter(DM_InvoiceNew.this,
				array_sort));
		myDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				stringArray = "";
				mapStLoadItemsInvoiceAdjusted();
				dialog.dismiss();
			}
		});
		myDialog.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						stringArray = "";
						dialog.dismiss();
					}
				});

		myalertDialog = myDialog.show();
	}

	// Map Sales Order Details After Adjusting Invoice Data
	protected void mapStLoadItemsInvoiceAdjusted() {
		// TODO Auto-generated method stub
		currentInvoiceNo();
		String StockOrderRef = etdmstorderno.getText().toString();
		String itemname = null, itemsincase = null, itemcode = null;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curstlitem = null;
		Cursor curselectitemchk = null;
		Cursor curselectitemdet = null;
		try {
			String checkQuery = "SELECT * FROM FOrddet FO Where FO.RefNo ='"
					+ StockOrderRef + "' group by FO.Itemcode,FO.Type";
			curstlitem = mydb.rawQuery(checkQuery, null);
		} catch (Exception e) {
		}

		if (curstlitem != null) {
			if (curstlitem.getCount() > 0) {
				while (curstlitem.moveToNext()) {
					ContentValues newrowfItemsConVal = new ContentValues();
					String Amt = curstlitem.getString(1);
					String BAmt = curstlitem.getString(2);
					String BDisAmt = curstlitem.getString(3);
					String BSellPrice = curstlitem.getString(4);
					String BTSellPrice = curstlitem.getString(5);
					String BTaxAmt = curstlitem.getString(6);
					String BalQty = curstlitem.getString(7);
					String CaseQty = curstlitem.getString(8);
					String CostPrice = curstlitem.getString(9);
					String DisAmt = curstlitem.getString(10);
					String DisPer = curstlitem.getString(11);
					currentItemCode = curstlitem.getString(12);
					String PiceQty = curstlitem.getString(13);
					String Qty = curstlitem.getString(14);
					String ReaCode = curstlitem.getString(15);
					String RecordId = curstlitem.getString(16);
					String RefNo = curstlitem.getString(17);
					String SellPrice = curstlitem.getString(18);
					String SeqNo = curstlitem.getString(19);
					String TSellPrice = curstlitem.getString(20);
					String TaxAmt = curstlitem.getString(21);
					String TxnType = curstlitem.getString(22);
					String Txnseqno = curstlitem.getString(23);
					ItmTxnType = curstlitem.getString(24);
					String TxnDate = curstlitem.getString(25);
					String ItemDisPer = curstlitem.getString(27);
					String ItemDisPerVal = curstlitem.getString(28);
					String ReasonDescRec = curstlitem.getString(29);
					String ItemUnitPrice = curstlitem.getString(31);

					checkItemAvailability();
					// ---Get Current ItemsDetails------
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					try {
						curselectitemchk = mydb
								.query(ITEMS, null, "ItemCode='"
										+ currentItemCode + "'", null, null,
										null, null);
					} catch (Exception e) {
					}
					if (curselectitemchk != null) {
						if (curselectitemchk.getCount() > 0) {
							while (curselectitemchk.moveToNext()) {
								String itemskucode = curselectitemchk
										.getString(1);
								itemcode = curselectitemchk.getString(2);
								itemname = curselectitemchk.getString(4);
								itemsincase = curselectitemchk.getString(28);

							}
						}
					}
					curselectitemchk.close();

					// =========================================================
					/*
					 * double localQty = Double.parseDouble(Qty); double
					 * itemsInCase = Double.parseDouble(itemsincase);
					 */
					// ----------------Map Stock Load Details With Inv
					try {
						curselectitemdet = mydb.query(INV_DETAILS, null,
								"refInvoiceDetCode='"
										+ currentInvoiceTempRefCode
										+ "' AND Itemcode='" + currentItemCode
										+ "' AND TxnType='" + TxnType + "'",
								null, null, null, null);

					} catch (Exception e) {
					}
					// int QtyVal = Integer.parseInt(Qty);
					double localQty = Double.parseDouble(Qty);

					// int itemsincaseVal = Integer.parseInt(itemsincase);
					double itemsInCase = Double.parseDouble(itemsincase);
					/*
					 * Log.v(TAG, "XXXXXX 9999 :" + ItmTxnType + " =" +
					 * CurrentItemStockQty);
					 */

					CurrentItemStockQty = Double.parseDouble(currentQty);
					if (ItmTxnType.equals("SA") || ItmTxnType.equals("FI")) {
						if (CurrentItemStockQty > 0) {
							if (localQty > CurrentItemStockQty) {
								localQty = CurrentItemStockQty;
								Qty = Double.toString(localQty);
								BalQty = Double.toString(localQty);
								// Case Pieces Quantity Conversions
								if (itemsInCase < localQty) {
									noOfAdjustedCases = localQty / itemsInCase;
									noOfAdjustedPieces = localQty
											- (noOfAdjustedCases * itemsInCase);

									int CaseQtyint = Integer
											.valueOf(noOfAdjustedCases
													.intValue());
									int PiceQtyint = Integer
											.valueOf(noOfAdjustedPieces
													.intValue());

									CaseQty = Integer.toString(CaseQtyint);
									PiceQty = Integer.toString(PiceQtyint);
								} else {
									noOfAdjustedPieces = localQty;
									CaseQty = "0";
									// PiceQty =
									// Double.toString(noOfAdjustedPieces);
									int PiceQtyint = Integer
											.valueOf(noOfAdjustedPieces
													.intValue());
									PiceQty = Integer.toString(PiceQtyint);
								}

								// Log.v(TAG, "Adjusted Qty 1:"+itemname
								// +"|QTY :"+CurrentItemStockQty +"<"+Qty);
								QtyAdjustedItems = QtyAdjustedItems + itemname
										+ "/,";
								STOCKCHK = 999;

							} else {
								Qty = Double.toString(localQty);
								BalQty = Double.toString(localQty);
								// Log.v(TAG, "Adjusted Qty 2:"+itemname
								// +"|QTY :"+CurrentItemStockQty +"<"+Qty);
							}

							if (curselectitemdet == null
									|| curselectitemdet.getCount() < 1) {
								/*
								 * Log.v(TAG, "SA /FI Insert :" + itemname +
								 * "|QTY :" + Qty);
								 */
								// Log.v(TAG, "Inserted CaseQty  1 :"+itemname
								// +"|CaseQty :"+CaseQty);
								// Log.v(TAG, "Inserted PiceQty  1 :"+itemname
								// +"|PiceQty :"+PiceQty);

								NoOfItemsPerInvoice = NoOfItemsPerInvoice + 1;
								newrowfItemsConVal.put("Amt", Amt.trim());

								double RecheckInvVal = Double.parseDouble(Amt
										.replaceAll("[,]", ""));
								RecheckInvoiceValue = RecheckInvoiceValue
										+ RecheckInvVal;

								newrowfItemsConVal.put("BAmt", BAmt.trim());
								newrowfItemsConVal.put("BDisAmt",
										BDisAmt.trim());
								newrowfItemsConVal.put("BSellPrice",
										BSellPrice.trim());
								newrowfItemsConVal.put("BTSellPrice",
										BTSellPrice.trim());
								newrowfItemsConVal.put("BTaxAmt",
										BTaxAmt.trim());
								newrowfItemsConVal.put("BalQty", BalQty.trim());
								newrowfItemsConVal.put("CaseQty",
										CaseQty.trim());
								newrowfItemsConVal.put("CostPrice",
										CostPrice.trim());
								newrowfItemsConVal.put("DisAmt", DisAmt.trim());
								double RecheckDisVal = Double
										.parseDouble(DisAmt.replaceAll("[,]",
												""));
								RecheckInvoiceDiscount = RecheckInvoiceDiscount
										+ RecheckDisVal;

								newrowfItemsConVal.put("DisPer", DisPer.trim());
								newrowfItemsConVal.put("Itemcode",
										currentItemCode.trim());
								newrowfItemsConVal.put("PiceQty",
										PiceQty.trim());

								newrowfItemsConVal.put("Qty", Qty.trim());
								newrowfItemsConVal.put("ReaCode",
										ReaCode.trim());
								newrowfItemsConVal.put("Linkrec", "0");
								newrowfItemsConVal.put("RecordId",
										RecordId.trim());
								newrowfItemsConVal.put("RefNo",
										currentInvoiceTempRefCode);
								newrowfItemsConVal.put("SellPrice",
										SellPrice.trim());
								newrowfItemsConVal.put("SeqNo", SeqNo.trim());
								newrowfItemsConVal.put("TSellPrice",
										TSellPrice.trim());
								newrowfItemsConVal.put("TaxAmt", TaxAmt.trim());
								newrowfItemsConVal.put("TxnType",
										TxnType.trim());
								newrowfItemsConVal.put("Txnseqno",
										Txnseqno.trim());
								newrowfItemsConVal.put("Type",
										ItmTxnType.trim());
								newrowfItemsConVal.put("TxnDate",
										invDiliveryDate);
								newrowfItemsConVal.put("itemDescription",
										itemname);
								newrowfItemsConVal.put("refInvoiceDetNo",
										LatestInvNumberStr);
								newrowfItemsConVal.put("refInvoiceDetCode",
										currentInvoiceTempRefCode);
								newrowfItemsConVal.put("refInvitemCaseQty",
										itemsincase);
								newrowfItemsConVal.put("refInvStockOrderNo",
										RefNo.trim());
								newrowfItemsConVal.put("invdetSync", "0");
								newrowfItemsConVal
										.put("invsysdate",
												getAddDateTimeStringFormat()
														.toString());
								// Item discount percentage
								newrowfItemsConVal
										.put("itemdisper", ItemDisPer);
								// Item discount percentage calculated value
								newrowfItemsConVal.put("itemdisperval",
										ItemDisPerVal);
								// reason details ref code
								newrowfItemsConVal.put("reasonCode", ReaCode);
								// reason details description
								newrowfItemsConVal.put("reasonDesc",
										ReasonDescRec);
								newrowfItemsConVal.put("reasonDesc",
										ItemUnitPrice);
								newrowfItemsConVal.put("itemUnitPrice",
										UnitPrice);
								mydb.insert(INV_DETAILS, null,
										newrowfItemsConVal);
								// mydb.close();
							}

						} else {
							// Log.v(TAG, "Stock Out Items :"+itemname
							// +"|QTY :"+CurrentItemStockQty);
							/*
							 * Log.v(TAG, "SA /FI Fail :" + itemname + "|QTY :"
							 * + Qty);
							 */
							StockOutItems = StockOutItems + itemname + "/,";
							STOCKCHK = 999;
						}
						mydb.close();
					} else if (ItmTxnType.equals("UR")
							|| ItmTxnType.equals("MR")) {
						/*
						 * Log.v(TAG, "UR /MR Insert :" + itemname + "|QTY :" +
						 * Qty);
						 */
						// Log.v(TAG, "Inserted CaseQty  2 :"+itemname
						// +"|CaseQty :"+CaseQty);
						// Log.v(TAG, "Inserted PiceQty  2 :"+itemname
						// +"|PiceQty :"+PiceQty);
						NoOfItemsPerInvoice = NoOfItemsPerInvoice + 1;
						newrowfItemsConVal.put("Amt", Amt.trim());
						double RecheckRetInvVal = Double.parseDouble(Amt
								.replaceAll("[,]", ""));
						RecheckInvoiceValReturn = RecheckInvoiceValReturn
								+ RecheckRetInvVal;
						newrowfItemsConVal.put("BAmt", BAmt.trim());
						newrowfItemsConVal.put("BDisAmt", BDisAmt.trim());
						newrowfItemsConVal.put("BSellPrice", BSellPrice.trim());
						newrowfItemsConVal.put("BTSellPrice",
								BTSellPrice.trim());
						newrowfItemsConVal.put("BTaxAmt", BTaxAmt.trim());
						newrowfItemsConVal.put("BalQty", BalQty.trim());
						newrowfItemsConVal.put("CaseQty", CaseQty.trim());
						newrowfItemsConVal.put("CostPrice", CostPrice.trim());
						newrowfItemsConVal.put("DisAmt", DisAmt.trim());
						newrowfItemsConVal.put("DisPer", DisPer.trim());
						newrowfItemsConVal.put("Itemcode",
								currentItemCode.trim());
						newrowfItemsConVal.put("PiceQty", PiceQty.trim());
						newrowfItemsConVal.put("Qty", Qty.trim());
						newrowfItemsConVal.put("ReaCode", ReaCode.trim());
						newrowfItemsConVal.put("Linkrec", "0");
						newrowfItemsConVal.put("RecordId", RecordId.trim());
						newrowfItemsConVal.put("RefNo",
								currentInvoiceTempRefCode);
						newrowfItemsConVal.put("SellPrice", SellPrice.trim());
						newrowfItemsConVal.put("SeqNo", SeqNo.trim());
						newrowfItemsConVal.put("TSellPrice", TSellPrice.trim());
						newrowfItemsConVal.put("TaxAmt", TaxAmt.trim());
						newrowfItemsConVal.put("TxnType", TxnType.trim());
						newrowfItemsConVal.put("Txnseqno", Txnseqno.trim());
						newrowfItemsConVal.put("Type", ItmTxnType.trim());
						newrowfItemsConVal.put("TxnDate", TxnDate.trim());
						newrowfItemsConVal.put("itemDescription", itemname);
						newrowfItemsConVal.put("refInvoiceDetNo",
								LatestInvNumberStr);
						newrowfItemsConVal.put("refInvoiceDetCode",
								currentInvoiceTempRefCode);
						newrowfItemsConVal
								.put("refInvitemCaseQty", itemsincase);
						newrowfItemsConVal.put("refInvStockOrderNo",
								RefNo.trim());
						newrowfItemsConVal.put("invdetSync", "0");
						newrowfItemsConVal.put("invsysdate",
								getCurrentTimeString().toString());
						// Item discount percentage
						newrowfItemsConVal.put("itemdisper", ItemDisPer);
						// Item discount percentage calculated value
						newrowfItemsConVal.put("itemdisperval", ItemDisPerVal);
						// reason details ref code
						newrowfItemsConVal.put("reasonCode", ReaCode);
						// reason details description
						newrowfItemsConVal.put("reasonDesc", ReasonDescRec);
						newrowfItemsConVal.put("itemUnitPrice", UnitPrice);
						mydb.insert(INV_DETAILS, null, newrowfItemsConVal);
					}

					else {
						/*
						 * Log.v(TAG, "UR /MR Insert Fail:" + itemname +
						 * "|QTY :" + Qty);
						 */
					}
					mydb.close();
				}
			}
		}
		UpdateSalesOrder();
		UpdateMapInvSummary();
	}

	private void currentInvoiceNo() {
		// Log.v(TAG, "*****currentInvoiceNo*****");
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectLastinvrec = null;
		String columsup[] = { "tempRepInvSerial" };
		try {
			selectLastinvrec = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"repusername='" + currentUserTemp
							+ "' AND invlateststate='9'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (selectLastinvrec != null) {
			if (selectLastinvrec.getCount() > 0) {
				while (selectLastinvrec.moveToNext()) {
					String LatestInvCodeStr = selectLastinvrec.getString(3);
					LatestInvNumberStr = selectLastinvrec.getString(4);
					String LatestInvValueStr = selectLastinvrec.getString(7);

					if (LatestInvNumberStr.length() == 1) {
						String newInvNumberStr = "00000" + LatestInvNumberStr;
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ newInvNumberStr;
					} else if (LatestInvNumberStr.length() == 2) {
						String newInvNumberStr = "0000" + LatestInvNumberStr;
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ newInvNumberStr;
					} else if (LatestInvNumberStr.length() == 3) {
						String newInvNumberStr = "000" + LatestInvNumberStr;
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ newInvNumberStr;
					} else if (LatestInvNumberStr.length() == 4) {
						String newInvNumberStr = "00" + LatestInvNumberStr;
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ newInvNumberStr;
					} else if (LatestInvNumberStr.length() == 5) {
						String newInvNumberStr = "0" + LatestInvNumberStr;
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ newInvNumberStr;
					} else {
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ LatestInvNumberStr;
					}
				}
			} else {
				Toast.makeText(getApplicationContext(), "First Invoice 1****",
						Toast.LENGTH_SHORT).show();
			}
		} else {

			Toast.makeText(getApplicationContext(), "First Invoice 1****",
					Toast.LENGTH_SHORT).show();
		}
		selectLastinvrec.close();
		mydb.close();
	}

	protected void checkItemAvailability() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor chkItemavailable = null;

		try {
			chkItemavailable = mydb.query(ITEM_LOC_DETAILS, null, "ItemCode='"
					+ currentItemCode + "' AND LocCode='" + UserLocCode + "'",
					null, null, null, null);
		} catch (Exception e1) {
		}
		if (chkItemavailable != null) {
			if (chkItemavailable.getCount() > 0) {
				while (chkItemavailable.moveToNext()) {
					currentQty = chkItemavailable.getString(3);
					CurrentItemStockQty = Double.parseDouble(currentQty);
				}
			}
		}
		chkItemavailable.close();
		mydb.close();
	}

	protected void updateInvoiceSumTable() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "****updateInvoiceSumTable****");
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curCurrentSumRecord = null;
		try {
			String querySelectInvSum = "SELECT * From frepInvoiceSumery Where activeInvoice ='1'";
			curCurrentSumRecord = mydb.rawQuery(querySelectInvSum, null);
		} catch (Exception e) {

		}
		if (curCurrentSumRecord != null) {
			if (curCurrentSumRecord.getCount() > 0) {
				while (curCurrentSumRecord.moveToNext()) {
					ContentValues valueupdateInvSum = new ContentValues();
					String invUpdateSerial = curCurrentSumRecord.getString(0);
					/*
					 * Log.v(TAG, "****updateInvoiceSumTable****:" + invcuscode
					 * + ":" + invcusname);
					 */
					valueupdateInvSum.put("InvoiceCustomerCode", invcuscode);
					valueupdateInvSum.put("InvoiceCustomerName", invcusname);
					String DisPercentageVal = etdminvcusdis.getText()
							.toString();
					if (DisPercentageVal.trim().length() != 0) {
						valueupdateInvSum.put("activeInvCusDiscount",
								DisPercentageVal);
					} else {
						valueupdateInvSum.put("activeInvCusDiscount", "0.00");
					}

					String DisVal = etdminvCusdiscount.getText().toString();
					if (DisVal.trim().length() != 0) {
						valueupdateInvSum.put("activeInvCusDiscountValue",
								DisVal);
					} else {
						valueupdateInvSum.put("activeInvCusDiscountValue",
								"0.00");
					}
					valueupdateInvSum.put("activeInvoiceRemarks",
							etdminvremarks.getText().toString());
					mydb.update(TEMP_REP_INVOICESUMERY, valueupdateInvSum,
							"remprepinv_id=" + invUpdateSerial, null);
				}
			}
		}
		curCurrentSumRecord.close();
		mydb.close();
		return;
	}

	protected void reloadAllCustommers() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewcutommer);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.invoicecustommer, R.id.invcustomername };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curListCustomer = null;
		try {
			String querySelectDebtor = "SELECT RD.DebCode,RD.RouteCode,FD.DebName,FD.OutDis FROM fRouteDet RD,fDebtor FD Where FD.DebCode = RD.DebCode";
			curListCustomer = mydb.rawQuery(querySelectDebtor, null);
		} catch (Exception e) {
		}
		if (curListCustomer != null) {
			if (curListCustomer.getCount() > 0) {
				while (curListCustomer.moveToNext()) {
					String customercode = curListCustomer.getString(0);
					String customername = curListCustomer.getString(2);
					String customerdiscount = curListCustomer.getString(3);
					String columncusdet = customercode + "/" + customername
							+ "/" + customerdiscount;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", columncusdet);
					maptrdes.put("coldes_2", customercode + " : "
							+ customername);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_customer_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		curListCustomer.close();
		mydb.close();
		DM_List_Expand_Helper.getListViewSize(lvtypedes);
		return;
	}

	private void deviceName() {
		// TODO Auto-generated method stub
		String Model = android.os.Build.MODEL;
		String id = android.os.Build.ID;
		deviceUser = Model + "_" + id;
	}

	private void checkInvoiceSummary() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "****checkInvoiceSummary****");
		ActiveInvoice = "1";
		RepInvCode = TransTypePrefix.trim() + AgentPrefixType.trim()
				+ currentUserPrefix;

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor checkInvoiceSerial = null;

		try {
			checkInvoiceSerial = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"tempRepInvSerial='" + strLatestInvoiceSerial
							+ "' AND repusername='" + currentUserTemp + "'",
					null, null, null, null);
		} catch (Exception e) {
		}
		if (checkInvoiceSerial != null) {
			if (checkInvoiceSerial.getCount() <= 0) {
				try {

					ContentValues saveTempuserinvoice = new ContentValues();
					saveTempuserinvoice.put("repusername", currentUserTemp);
					saveTempuserinvoice.put("repprefix", currentUserPrefix);
					saveTempuserinvoice.put("tempRepInvNoCode", RepInvCode);
					saveTempuserinvoice.put("tempRepInvSerial",
							strLatestInvoiceSerial);
					saveTempuserinvoice.put("invoiceComplete", "0");
					saveTempuserinvoice.put("activeInvoice", ActiveInvoice);
					saveTempuserinvoice.put("activeInvoiceValue", "0");
					saveTempuserinvoice.put("activeInvItemDiscount", "0");
					saveTempuserinvoice.put("activeInvCusDiscount", "0");
					saveTempuserinvoice.put("activeInvCusDiscountValue", "0");
					saveTempuserinvoice.put("InvoiceCustomerCode", "0");
					saveTempuserinvoice.put("InvoiceCustomerName", "");
					saveTempuserinvoice.put("InvoiceSynchState", "0");
					saveTempuserinvoice.put("recordDate",
							getCurrentTimeStringCustom());
					saveTempuserinvoice.put("recordSynchDate", "0");
					saveTempuserinvoice.put("invlateststate", "9");
					saveTempuserinvoice.put("activeInvoiceReturnValue", "0");
					saveTempuserinvoice.put("activeInvoiceRemarks", " ");
					saveTempuserinvoice.put("invoiceNoOfItems", "0");
					saveTempuserinvoice.put("invoiceRef", "0");
					saveTempuserinvoice.put("invoiceRefStl", "");

					mydb.insert(TEMP_REP_INVOICESUMERY, null,
							saveTempuserinvoice);
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(),
							"Error Occured D..", Toast.LENGTH_SHORT).show();
				}

			}
		}
		checkInvoiceSerial.close();
		mydb.close();
		return;
	}

	// *******Get Latest Invoice Serial**********
	private void checkLatestInvoiceSerial() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "****checkLatestInvoiceSerial****");
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectInvoiceSerial = null;

		try {
			selectInvoiceSerial = mydb.query(INV_COMPANY_BRANCH, null,
					"cSettingsCode='SECINV' AND BranchCode='" + currentUserTemp
							+ "'", null, null, null, null);
		} catch (Exception e) {
		}

		if (selectInvoiceSerial != null) {
			if (selectInvoiceSerial.getCount() > 0) {
				while (selectInvoiceSerial.moveToNext()) {
					String cSettingsCode = selectInvoiceSerial.getString(3);
					String nNumVal = selectInvoiceSerial.getString(4);
					strLatestInvoiceSerial = nNumVal.trim();
				}
			} else {
				strLatestInvoiceSerial = "1";
				try {
					ContentValues newAdjustment = new ContentValues();
					newAdjustment.put("BranchCode", currentUserTemp);
					newAdjustment.put("RecordId", "1");
					newAdjustment.put("cSettingsCode", "SECINV");
					newAdjustment.put("nNumVal", strLatestInvoiceSerial);
					mydb.insert(INV_COMPANY_BRANCH, null, newAdjustment);

				} catch (Exception e) {
					Toast.makeText(this, e.toString(), Toast.LENGTH_LONG)
							.show();
				}
				mydb.close();
			}
		}
		selectInvoiceSerial.close();
		mydb.close();
		return;
	}

	// +++++++++++Show Invoice List++++++++++++++++++++++++++++++
	protected void ShowInvoiceList() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "****ShowInvoiceList****");
		String currentuser = currentUserTemp.toUpperCase();
		ListView InvoicesList = (ListView) findViewById(R.id.listviewInvoices);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colinvoice_1", "colinvoice_2" };
		int[] totrdes = new int[] { R.id.invListingViewNo,
				R.id.invListingViewSum };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;
		try {
			String queryListInv = "SELECT * FROM frepInvoiceSumery WHERE repusername='"
					+ currentUserTemp
					+ "' AND invoiceComplete ='2' ORDER BY invoiceRef DESC";
			allrowtypedes = mydb.rawQuery(queryListInv, null);

			/*
			 * allrowtypedes = mydb.query(TEMP_REP_INVOICESUMERY, null,
			 * "repusername='" + currentUserTemp + "' AND invoiceComplete ='2'",
			 * null, null, null, null);
			 */

		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					String remprepinv_id = allrowtypedes.getString(0);
					String tempRepInvNoCode = allrowtypedes.getString(3);
					String tempRepInvSerial = allrowtypedes.getString(4);
					String debtor = allrowtypedes.getString(12);
					String invRefNo = allrowtypedes.getString(20);
					String columncusdet = remprepinv_id + "/"
							+ tempRepInvNoCode + "/" + tempRepInvSerial;
					String flagno = "00000";
					String PrintRefNo = tempRepInvNoCode + "/" + flagno
							+ tempRepInvSerial;
					// Log.v(TAG, "LIST RESULT :" + PrintRefNo + " - " +
					// debtor);
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("colinvoice_1", PrintRefNo + " - " + debtor);
					maptrdes.put("colinvoice_2", invRefNo);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_pre_invoice_list_raw,
						fromtrdes, totrdes);
				InvoicesList.setAdapter(adaptertrdes);
			}
		}
		allrowtypedes.close();
		mydb.close();
		return;
		// DM_List_Expand_Helper.getListViewSize(InvoicesList);
	}

	// ******View Avilable Sales Oreder Numbers In List View********
	protected void ShowStockOrdersList() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "****ShowStockOrdersList****");
		ListView lvtypedes = (ListView) findViewById(R.id.listviewdmstockorders);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colinvoice_1", "colinvoice_2" };
		int[] totrdes = new int[] { R.id.invListingStorderViewNo,
				R.id.invListingStorderViewSum };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curStOrdListItem = null;
		try {
			/*
			 * curStOrdListItem = mydb.query(STOCK_ORDER_HEAD, null, "RepCode='"
			 * + currentUserTemp.toUpperCase() + "' AND stOrderComplete='0'",
			 * null, null, null, null);
			 */
			String query = "SELECT OH.RefNo,OH.AddUser,OH.DebCode,OH.LocCode,OH.RecordId,OH.RepCode,DE.DebCode,DE.DebName,DE.TownCode,TW.TownCode,TW.TownName,OS.remprepinv_id,OS.invoiceComplete,OS.repusername,OS.invoiceComplete,OS.tempRepInvNoCode,OS.tempRepInvSerial,OH.stOrderComplete FROM FOrdHed OH INNER JOIN fDebtor DE ON DE.DebCode = OH.DebCode INNER JOIN fTown TW ON TW.TownCode = DE.TownCode INNER JOIN fstockordInvoiceSumery  OS ON OS.invoiceRef = OH.RefNo Where OH.RepCode ='"
					+ currentUserTemp.toUpperCase()
					+ "' AND OH.stOrderComplete ='0' AND OS.invoiceComplete ='2' group by OH.RefNo order by OH.RefNo DESC";
			curStOrdListItem = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (curStOrdListItem != null) {
			if (curStOrdListItem.getCount() > 0) {
				while (curStOrdListItem.moveToNext()) {
					String RefNo = curStOrdListItem.getString(0);
					String DebCode = curStOrdListItem.getString(2);
					String LocCode = curStOrdListItem.getString(3);
					String RecordId = curStOrdListItem.getString(4);
					String RepCode = curStOrdListItem.getString(5);
					String DebName = curStOrdListItem.getString(7);
					String TownName = curStOrdListItem.getString(10);
					String columncusdet = DebCode + "/" + LocCode + "/"
							+ RecordId;

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("colinvoice_1", RefNo + " - " + DebName);
					maptrdes.put("colinvoice_2", RefNo);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_stock_orders_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		curStOrdListItem.close();
		mydb.close();
		return;
		// DM_List_Expand_Helper.getListViewSize(lvtypedes);
	}

	private void currentuserTemp() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "****currentuserTemp****");
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserrec = null;
		try {
			selectCurrentuserrec = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserrec != null) {
			if (selectCurrentuserrec.getCount() > 0) {
				while (selectCurrentuserrec.moveToNext()) {
					currentUserTemp = selectCurrentuserrec.getString(1);
					currentUserPrefix = selectCurrentuserrec.getString(2);
					UserLocCode = selectCurrentuserrec.getString(5);
					UserAreaCode = selectCurrentuserrec.getString(9);
					UserDealCode = selectCurrentuserrec.getString(10);
					UserRouteCode = selectCurrentuserrec.getString(11);

					String currentUserStRef = selectCurrentuserrec.getString(4);
					if (currentUserStRef.equals("0") && TagId.equals(match)) {
						etdmstorderno.setEnabled(false);
					}

				}
			}
		}
		latestInvoiceNumber();// Get current invoice temp
		selectCurrentuserrec.close();
		mydb.close();
		return;
	}

	private void latestInvoiceNumber() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "****latestInvoiceNumber****");
		ListInvTag = 77;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor latestinvoicerowdet = null;
		try {
			latestinvoicerowdet = mydb
					.query(TEMP_REP_INVOICESUMERY,
							null,
							"repusername='"
									+ currentUserTemp
									+ "' AND invoiceComplete='1' OR invoiceComplete='0'",
							null, null, null, null);
		} catch (Exception e) {
		}
		if (latestinvoicerowdet != null) {
			if (latestinvoicerowdet.getCount() > 0) {

				while (latestinvoicerowdet.moveToNext()) {

					String repusername = latestinvoicerowdet.getString(1);
					invoiceSerial = latestinvoicerowdet.getString(4);
					String invoiceComplete = latestinvoicerowdet.getString(5);
					String activeInvoiceValue = latestinvoicerowdet
							.getString(7);// Take tot val
					String activeInvItemDiscount = latestinvoicerowdet
							.getString(8);
					String activeInvCusDiscount = latestinvoicerowdet
							.getString(9);// cus discount rate
					String activeInvCusDiscountValue = latestinvoicerowdet
							.getString(10);
					invcuscode = latestinvoicerowdet.getString(11);
					invcusname = latestinvoicerowdet.getString(12);
					String recordDate = latestinvoicerowdet.getString(14);
					String activeInvoiceReturnValue = latestinvoicerowdet
							.getString(17);
					String activeInvoiceremark = latestinvoicerowdet
							.getString(18);
					String invoiceRef = latestinvoicerowdet.getString(20);
					String invoiceStOrdRef = latestinvoicerowdet.getString(21);
					invoicetotval.setText(activeInvoiceValue);
					if (invoiceComplete.equals("0")) {
						etdmstorderno.setText(invoiceStOrdRef);
						etdminvcustomer.setText(invcusname);
						etdminvcusdis.setText(activeInvCusDiscount);
					} else {
						if (TagId.equals("3")) {
							if (invoiceRef.equals("0")) {
								// Print Date
								etdminvdate.setText(recordDate);
								// Customer name
								etdminvcustomer.setText(invcusname);
								// Invoice remarks
								etdminvremarks.setText(activeInvoiceremark);
								// Invoice market return value
								marketretval.setText(activeInvoiceReturnValue);
								// Discount Value

								StrMainLineDisValTot = Double
										.parseDouble(activeInvItemDiscount
												.replaceAll("[,]", ""));
								activeInvItemDiscount = formatValues
										.format(StrMainLineDisValTot);
								invoicedisval.setText(activeInvItemDiscount);
								// Invoice Total
								invoicetotval.setText(activeInvoiceValue);
								StrMainInvValTot = Double
										.parseDouble(activeInvoiceValue
												.replaceAll("[,]", ""));

								// Customer Discount Ratio
								etdminvcusdis.setText(activeInvCusDiscount);
								// Customer Discount Value
								etdminvCusdiscount
										.setText(activeInvCusDiscountValue);
							}
						} else if (TagId.equals(match)) {
							INVSave.setEnabled(true);
							INVCancel.setEnabled(true);
							INVUndo.setEnabled(true);
							viewInvoiceHeaderDetails();
						}
					}

				}
			}
		} else {
			Toast.makeText(getApplicationContext(), "Enter New Invoice***",
					Toast.LENGTH_SHORT).show();
		}
		latestinvoicerowdet.close();
		mydb.close();
		return;
	}

	private void viewInvoiceHeaderDetails() {
		etdminvCusdiscount.setEnabled(true);
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor latestinvoicerow = null;
		try {
			latestinvoicerow = mydb.query(TEMP_REP_INVOICESUMERY, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (latestinvoicerow != null) {
			if (latestinvoicerow.getCount() > 0) {
				while (latestinvoicerow.moveToNext()) {

					String repusername = latestinvoicerow.getString(1);
					String tempRepInvNoCode = latestinvoicerow.getString(3);
					invoiceSerial = latestinvoicerow.getString(4);
					String tempRepInvSerial = latestinvoicerow.getString(4);
					String invoiceComplete = latestinvoicerow.getString(5);
					String activeInvoiceValue = latestinvoicerow.getString(7);// Take
																				// tot
																				// val
					String activeInvItemDiscount = latestinvoicerow
							.getString(8);
					String activeInvCusDiscount = latestinvoicerow.getString(9);// cus
																				// discount
																				// rate
					String activeInvCusDiscountValue = latestinvoicerow
							.getString(10);
					invcuscode = latestinvoicerow.getString(11);
					invcusname = latestinvoicerow.getString(12);
					String recordDate = latestinvoicerow.getString(14);
					String activeInvoiceReturnValue = latestinvoicerow
							.getString(17);
					String activeInvoiceremark = latestinvoicerow.getString(18);
					String invoiceRef = latestinvoicerow.getString(20);
					String invoiceStOrdRef = latestinvoicerow.getString(21);

					etdmstorderno.setText(invoiceStOrdRef);
					// Print Date
					etdminvdate.setText(recordDate);
					// Customer name
					etdminvcustomer.setText(invcusname);
					// Invoice remarks
					etdminvremarks.setText(activeInvoiceremark);
					// Market return total value
					marketretval.setText(activeInvoiceReturnValue);
					// Discount Value
					// invoicedisval.setText(activeInvItemDiscount);
					StrMainLineDisValTot = Double
							.parseDouble(activeInvItemDiscount.replaceAll(
									"[,]", ""));
					// Invoice Total
					// invoicetotval.setText(activeInvoiceValue);
					StrMainInvValTot = Double.parseDouble(activeInvoiceValue
							.replaceAll("[,]", ""));

					// Customer Discount Ratio
					etdminvcusdis.setText(activeInvCusDiscount);
					// Customer Discount Value
					etdminvCusdiscount.setText(activeInvCusDiscountValue);

					// Total Invoice Percentage Discount Value
					InvValueItems = Double.parseDouble(activeInvoiceValue
							.replaceAll("[,]", "").trim());// Invoice Tot Val
					// CustomerDiscout Rate
					InvDiscountValueCustomer = Double
							.parseDouble(activeInvCusDiscount.replaceAll("[,]",
									""));
					TotCustomerInvDiscount = (InvValueItems * InvDiscountValueCustomer) / 100;
					TotCustomerInvDiscount = Math
							.round(TotCustomerInvDiscount * 100) / 100.0d;
					PrintTotCustomerInvDiscount = Double
							.toString(TotCustomerInvDiscount);
					// ********************************************************************

					try {
						if (tempRepInvSerial.length() == 1) {
							String newInvNumberStr = "00000" + tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						} else if (tempRepInvSerial.length() == 2) {
							String newInvNumberStr = "0000" + tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						} else if (tempRepInvSerial.length() == 3) {
							String newInvNumberStr = "000" + tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						} else if (tempRepInvSerial.length() == 4) {
							String newInvNumberStr = "00" + tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						} else if (tempRepInvSerial.length() == 5) {
							String newInvNumberStr = "0" + tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						} else {
							String newInvNumberStr = tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						}

						etdminvno.setText(currentInvoiceTempRefCode);
						etdminvdiscount.setText(PrintTotCustomerInvDiscount);

					} catch (Exception e) {
						Toast.makeText(getApplicationContext(),
								"Error Occured E..", Toast.LENGTH_SHORT).show();
					}
				}
			}
		}
		latestinvoicerow.close();
		mydb.close();
		return;
	}

	private void populateCustomerList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewcutommer);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.invoicecustommer, R.id.invcustomername };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;
		try {
			if (customerReloadTag == 202) {
				String querySelectDebtor = "SELECT RD.DebCode,RD.RouteCode,FD.DebName,FD.OutDis FROM fRouteDet RD,fDebtor FD Where FD.DebCode = RD.DebCode AND RD.RouteCode ='"
						+ UserRouteCode + "'";
				allrowtypedes = mydb.rawQuery(querySelectDebtor, null);
			} else if (customerReloadTag == 404) {
				populateCustomerDetailsList();
			}

		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					CustomerCodeInv = allrowtypedes.getString(0);
					// checkInvoicedCustomer();
					String customername = allrowtypedes.getString(2);
					String customerdiscount = allrowtypedes.getString(3);
					String columncusdet = CustomerCodeInv + "/" + customername
							+ "/" + customerdiscount;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", CustomerCodeInv);
					maptrdes.put("coldes_2", CustomerCodeInv + " : "
							+ customername);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_customer_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
				lvtypedes.setSmoothScrollbarEnabled(true);

			}
		}
		allrowtypedes.close();
		mydb.close();
		return;
	}

	private void checkInvoicedCustomer() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curChkCustomerInvoiced = null;

		try {
			String queryChkInvCustomer = "SELECT DebCode FROM FinvHed Where DebCode ='"
					+ CustomerCodeInv
					+ "' AND TxnDate ='"
					+ getCurrentTimeStringCustom().toString() + "'";
			curChkCustomerInvoiced = mydb.rawQuery(queryChkInvCustomer, null);
		} catch (Exception e) {
		}

		if (curChkCustomerInvoiced != null) {
			if (curChkCustomerInvoiced.getCount() > 0) {
				while (curChkCustomerInvoiced.moveToNext()) {
					INVICEDCUSTAG = 1;
				}
			} else {
				INVICEDCUSTAG = 0;
			}
		} else {
			// Log.v(TAG, "*******populateCustomerDetailsList*******");
		}
		curChkCustomerInvoiced.close();
		mydb.close();
		return;
	}

	@SuppressLint("NewApi")
	private void populateCustomerDetailsList() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*******populateCustomerDetailsList*******");
		Cursor cursor = dbHelperCustomer.fetchAllCustommers();

		// The desired columns to be bound
		String[] columns = new String[] { DM_CustomerList_Adapter.KEY_CUSCODE,
				DM_CustomerList_Adapter.KEY_CUSNAME };
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		// the XML defined views which the data will be bound to
		int[] to = new int[] { R.id.invoicecustommer, R.id.invcustomername, };

		// create the adapter using the cursor pointing to the desired data
		// as well as the layout information
		dataAdapterCusomer = new SimpleCursorAdapter(this,
				R.layout.dm_customer_list_raw, cursor, columns, to, 0);

		ListView listView = (ListView) findViewById(R.id.listviewcutommer);
		// Assign adapter to ListView
		listView.setAdapter(dataAdapterCusomer);

		myFilterCustomer.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				dataAdapterCusomer.getFilter().filter(s.toString());
			}
		});

		dataAdapterCusomer.setFilterQueryProvider(new FilterQueryProvider() {
			public Cursor runQuery(CharSequence constraint) {
				return dbHelperCustomer.fetchAllCustommersByName(constraint
						.toString());
			}
		});
	}

	private String getCurrentTimeString() {
		Calendar c = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String formattedDate = df.format(c.getTime());
		return formattedDate;
	}

	private String getCurrentTimeStringCustom() {
		// 2013-10-04 00:00:00.000
		// Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(c.getTime());
		return date_to_string;
	}

	private String getAddDateTimeStringFormat() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

	// Handling Dialog Box Functions
	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_CANCEL_INVOICE:
			LayoutInflater inflater = LayoutInflater.from(this);
			View dialogview = inflater.inflate(
					R.layout.dm_dialog_cancel_invoice, null);

			AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
			dialogbuilder.setTitle("Cancel Current Invoice Details...");
			dialogbuilder.setView(dialogview);
			InvoiceHeaderAlert = dialogbuilder.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);

			break;

		case DIALOG_UNDO_INVOICE:
			LayoutInflater inflateru = LayoutInflater.from(this);
			View dialogviewu = inflateru.inflate(
					R.layout.dm_dialog_undo_invoice, null);

			AlertDialog.Builder dialogbuilderu = new AlertDialog.Builder(this);
			dialogbuilderu.setTitle("Undo Current Invoice Details...");
			dialogbuilderu.setView(dialogviewu);
			InvoiceHeaderAlert = dialogbuilderu.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_PRINT_INVOICE:
			LayoutInflater inflaterp = LayoutInflater.from(this);
			View dialogviewp = inflaterp.inflate(
					R.layout.dm_dialog_print_invoice, null);

			AlertDialog.Builder dialogbuilderp = new AlertDialog.Builder(this);
			dialogbuilderp.setTitle("Printing Configuration Failure...");
			dialogbuilderp.setView(dialogviewp);
			InvoiceHeaderAlert = dialogbuilderp.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_SAVE_INVOICE:
			LayoutInflater inflaters = LayoutInflater.from(this);
			View dialogviews = inflaters.inflate(
					R.layout.dm_dialog_save_invoice, null);

			AlertDialog.Builder dialogbuilders = new AlertDialog.Builder(this);
			dialogbuilders.setTitle("Invoice Saved Successfully...");
			dialogbuilders.setView(dialogviews);
			InvoiceHeaderAlert = dialogbuilders.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_SELECT_CUSTOMER:
			LayoutInflater inflatercus = LayoutInflater.from(this);
			View dialogviewcus = inflatercus.inflate(
					R.layout.dm_dialog_select_customer, null);

			AlertDialog.Builder dialogbuildercus = new AlertDialog.Builder(this);
			dialogbuildercus.setTitle("Please Select Customer...");
			dialogbuildercus.setView(dialogviewcus);
			InvoiceHeaderAlert = dialogbuildercus.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_MUSTSALE_ITEMS:
			LayoutInflater inflatercusms = LayoutInflater.from(this);
			View dialogviewcusms = inflatercusms.inflate(
					R.layout.dm_dialog_chk_must_sale, null);

			AlertDialog.Builder dialogbuildercusms = new AlertDialog.Builder(
					this);
			dialogbuildercusms.setTitle("MUST SALE ITEM");
			dialogbuildercusms
					.setMessage("There is no MUST SALE item in this invoice ! Do You Want To proceed ?...");
			dialogbuildercusms.setView(dialogviewcusms);
			InvoiceHeaderAlert = dialogbuildercusms.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;
		}

		return InvoiceHeaderAlert;
	}

	// ***********************************************************************************
	// Calculate Values With Discount Ratio
	private TextWatcher calculateCustomerInvDiscount = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			if (etdminvcusdis.length() != 0 && etdminvCusdiscount.length() == 0) {
				StrManualInvAmount = 0.00;
				// Calculate Discount Percentage Ratio
				String StrInvDisRatio = etdminvcusdis.getText().toString();
				StrInvDisRatioAmount = Double.parseDouble(StrInvDisRatio
						.replaceAll("[,]", ""));
				ratio = StrInvDisRatioAmount / 100.00;

				if (ratio > 1) {
					callDiscountRatioExceedAlert();
				} else {
					// Do Calculations
					double discountedTotValRatioVal = StrMainInvValTot * ratio;
					String PrintdiscountedTotValRatioVal = formatValues
							.format(discountedTotValRatioVal);
					etdminvdiscount.setText(PrintdiscountedTotValRatioVal);

					// Calculate Current Total Dicount Value
					double newDiscountTot = StrMainLineDisValTot
							+ discountedTotValRatioVal;
					String PrintnewDiscountTot = formatValues
							.format(newDiscountTot);
					invoicedisval.setText(PrintnewDiscountTot);

					// Calculate Current Invoice Value
					double newDiscountedTotVal = StrMainInvValTot
							- discountedTotValRatioVal;
					String PrintnewDiscountedTotVal = formatValues
							.format(newDiscountedTotVal);
					invoicetotval.setText(PrintnewDiscountedTotVal);
				}
			} else if (etdminvcusdis.length() != 0
					&& etdminvCusdiscount.length() != 0) {
				// Calculate Discount Percentage Ratio
				String StrInvDisRatio = etdminvcusdis.getText().toString();
				StrInvDisRatioAmount = Double.parseDouble(StrInvDisRatio
						.replaceAll("[,]", ""));
				ratio = StrInvDisRatioAmount / 100.00;

				if (ratio > 1) {
					callDiscountRatioExceedAlert();
				} /*
				 * else if (StrManualDiscount > StrMainInvValTot) {
				 * //callDiscountValueAmtExceed(); StrManualDiscount = 0.00;
				 * etdminvCusdiscount.setText("0.00"); }
				 */else {
					String StrInvDiscountHedVal = etdminvCusdiscount.getText()
							.toString();
					double StrInvDiscountHedAmount = Double
							.parseDouble(StrInvDiscountHedVal.replaceAll("[,]",
									""));

					// Do Calculations
					double discountedTotValRatioVal = StrMainInvValTot * ratio;
					String PrintdiscountedTotValRatioVal = formatValues
							.format(discountedTotValRatioVal);
					etdminvdiscount.setText(PrintdiscountedTotValRatioVal);

					// Calculate Current Total Dicount Value
					double newDiscountTot = StrMainLineDisValTot
							+ discountedTotValRatioVal
							+ StrInvDiscountHedAmount;
					String PrintnewDiscountTot = formatValues
							.format(newDiscountTot);
					invoicedisval.setText(PrintnewDiscountTot);

					// Calculate Current Invoice Value
					double headerTotDiscount = discountedTotValRatioVal
							+ StrInvDiscountHedAmount;
					double newDiscountedTotVal = StrMainInvValTot
							- headerTotDiscount;
					String PrintnewDiscountedTotVal = formatValues
							.format(newDiscountedTotVal);
					invoicetotval.setText(PrintnewDiscountedTotVal);
				}
			} else if (etdminvcusdis.length() == 0
					&& etdminvCusdiscount.length() != 0) {
				String StrInvDiscountHedVal = etdminvCusdiscount.getText()
						.toString();
				double StrInvDiscountHedAmount = Double
						.parseDouble(StrInvDiscountHedVal.replaceAll("[,]", ""));

				// Do Calculations
				etdminvdiscount.setText("0.00");

				// Calculate Current Total Dicount Value
				double newDiscountTot = StrMainLineDisValTot
						+ StrInvDiscountHedAmount;
				String PrintnewDiscountTot = formatValues
						.format(newDiscountTot);
				invoicedisval.setText(PrintnewDiscountTot);

				// Calculate Current Invoice Value
				double newDiscountedTotVal = StrMainInvValTot
						- StrInvDiscountHedAmount;
				String PrintnewDiscountedTotVal = formatValues
						.format(newDiscountedTotVal);
				invoicetotval.setText(PrintnewDiscountedTotVal);
			} else {
				etdminvdiscount.setText("0.00");
				// print discountcc
				String newStrMainInvDisValTot = formatValues
						.format(StrMainLineDisValTot);
				invoicedisval.setText(newStrMainInvDisValTot);
				// print total
				String newStrMainInvValTot = formatValues
						.format(StrMainInvValTot);
				invoicetotval.setText(newStrMainInvValTot);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub

		}

	};

	// ***********************************************************************************
	private TextWatcher calculateCusInvDisManuVal = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			if (etdminvcusdis.length() != 0 && etdminvCusdiscount.length() == 0) {
				StrManualInvAmount = 0.00;
				// Calculate Discount Percentage Ratio
				String StrInvDisRatio = etdminvcusdis.getText().toString();
				StrInvDisRatioAmount = Double.parseDouble(StrInvDisRatio
						.replaceAll("[,]", ""));
				ratio = StrInvDisRatioAmount / 100.00;

				if (ratio > 1) {
					callDiscountRatioExceedAlert();
				} else {
					// Do Calculations
					double discountedTotValRatioVal = StrMainInvValTot * ratio;
					String PrintdiscountedTotValRatioVal = formatValues
							.format(discountedTotValRatioVal);
					etdminvdiscount.setText(PrintdiscountedTotValRatioVal);

					// Calculate Current Total Dicount Value
					double newDiscountTot = StrMainLineDisValTot
							+ discountedTotValRatioVal;
					String PrintnewDiscountTot = formatValues
							.format(newDiscountTot);
					invoicedisval.setText(PrintnewDiscountTot);

					// Calculate Current Invoice Value
					double newDiscountedTotVal = StrMainInvValTot
							- discountedTotValRatioVal;
					String PrintnewDiscountedTotVal = formatValues
							.format(newDiscountedTotVal);
					invoicetotval.setText(PrintnewDiscountedTotVal);
				}
			} else if (etdminvcusdis.length() != 0
					&& etdminvCusdiscount.length() != 0) {
				// Calculate Discount Percentage Ratio
				String StrInvDisRatio = etdminvcusdis.getText().toString();
				StrInvDisRatioAmount = Double.parseDouble(StrInvDisRatio
						.replaceAll("[,]", ""));
				ratio = StrInvDisRatioAmount / 100.00;

				if (ratio > 1) {
					callDiscountRatioExceedAlert();
				}/*
				 * else if (StrManualDiscount > StrMainInvValTot) {
				 * //callDiscountValueAmtExceed(); StrManualDiscount = 0.00; }
				 */else {
					String StrInvDiscountHedVal = etdminvCusdiscount.getText()
							.toString();
					double StrInvDiscountHedAmount = Double
							.parseDouble(StrInvDiscountHedVal.replaceAll("[,]",
									""));

					// Do Calculations
					double discountedTotValRatioVal = StrMainInvValTot * ratio;
					String PrintdiscountedTotValRatioVal = formatValues
							.format(discountedTotValRatioVal);
					etdminvdiscount.setText(PrintdiscountedTotValRatioVal);

					// Calculate Current Total Dicount Value
					double newDiscountTot = StrMainLineDisValTot
							+ discountedTotValRatioVal
							+ StrInvDiscountHedAmount;
					String PrintnewDiscountTot = formatValues
							.format(newDiscountTot);
					invoicedisval.setText(PrintnewDiscountTot);

					// Calculate Current Invoice Value
					double headerTotDiscount = discountedTotValRatioVal
							+ StrInvDiscountHedAmount;
					double newDiscountedTotVal = StrMainInvValTot
							- headerTotDiscount;
					String PrintnewDiscountedTotVal = formatValues
							.format(newDiscountedTotVal);
					invoicetotval.setText(PrintnewDiscountedTotVal);
				}
			} else if (etdminvcusdis.length() == 0
					&& etdminvCusdiscount.length() != 0) {
				String StrInvDiscountHedVal = etdminvCusdiscount.getText()
						.toString();
				double StrInvDiscountHedAmount = Double
						.parseDouble(StrInvDiscountHedVal.replaceAll("[,]", ""));

				// Do Calculations
				etdminvdiscount.setText("0.00");

				// Calculate Current Total Dicount Value
				double newDiscountTot = StrMainLineDisValTot
						+ StrInvDiscountHedAmount;
				String PrintnewDiscountTot = formatValues
						.format(newDiscountTot);
				invoicedisval.setText(PrintnewDiscountTot);

				// Calculate Current Invoice Value
				double newDiscountedTotVal = StrMainInvValTot
						- StrInvDiscountHedAmount;
				String PrintnewDiscountedTotVal = formatValues
						.format(newDiscountedTotVal);
				invoicetotval.setText(PrintnewDiscountedTotVal);
			} else {
				etdminvdiscount.setText("0.00");
				// print discountcc
				String newStrMainInvDisValTot = formatValues
						.format(StrMainLineDisValTot);
				invoicedisval.setText(newStrMainInvDisValTot);
				// print total
				String newStrMainInvValTot = formatValues
						.format(StrMainInvValTot);
				invoicetotval.setText(newStrMainInvValTot);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub

		}
	};

	protected void callDiscountRatioExceedAlert() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(
				DM_InvoiceNew.this).create();
		// Setting Dialog Title
		alertDialog.setTitle("ITEMS DISCOUNTING");
		// Setting Dialog Message
		alertDialog
				.setMessage("Invalid Appcation Invoice Discount Items Percentage.Maximum Percentage Allowed 100%");
		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.warning);
		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(final DialogInterface dialog, final int which) {
				ratio = 0.00;
				ratioManu = 0.00;
				etdminvcusdis.setText("");
				alertDialog.dismiss();
			}
		});
		// Showing Alert Message
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);
		return;

	}

	protected void callDiscountValueAmtExceed() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(
				DM_InvoiceNew.this).create();
		// Setting Dialog Title
		alertDialog.setTitle("INVALID INVOICE DISCOUNTING");
		// Setting Dialog Message
		alertDialog
				.setMessage("Total Invoice Discount Exceed.Discount Amount Can't Exceed Total Invoice Value..");
		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.warning);
		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(final DialogInterface dialog, final int which) {
				StrManualDiscount = 0.00;
				etdminvCusdiscount.setText("");
				alertDialog.dismiss();
			}
		});
		// Showing Alert Message
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);
		return;
	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	// ==================================
	public class DecimalDigitsInputFilter implements InputFilter {

		private final int decimalDigits;

		/**
		 * Constructor.
		 * 
		 * @param decimalDigits
		 *            maximum decimal digits
		 */
		public DecimalDigitsInputFilter(int decimalDigits) {
			this.decimalDigits = decimalDigits;
		}

		@Override
		public CharSequence filter(CharSequence source, int start, int end,
				Spanned dest, int dstart, int dend) {

			int dotPos = -1;
			int len = dest.length();
			for (int i = 0; i < len; i++) {
				char c = dest.charAt(i);
				if (c == '.' || c == ',') {
					dotPos = i;
					break;
				}
			}
			if (dotPos >= 0) {

				// protects against many dots
				if (source.equals(".") || source.equals(",")) {
					return "";
				}
				// if the text is entered before the dot
				if (dend <= dotPos) {
					return null;
				}
				if (len - dotPos > decimalDigits) {
					return "";
				}
			}

			return null;
		}

	}
}
